如何使用javascript验证用户输入(字符和数字)?
从 我尝试在单击按钮时验证用户输入如何使用javascript验证用户输入(字符和数字)?,javascript,jquery,Javascript,Jquery,从 我尝试在单击按钮时验证用户输入 $("#check_data").click(function () { var $userInput = $('#user_input'); //from HTML input box id="user_input" var pattern = " /*My user input always be like "AB1234567"*/ "; if ($userInput.val() == '' || !pattern.test($u
$("#check_data").click(function () {
var $userInput = $('#user_input'); //from HTML input box id="user_input"
var pattern = " /*My user input always be like "AB1234567"*/ ";
if ($userInput.val() == '' || !pattern.test($userInput.val())) {
alert('Please enter a valid code.');
return false;
}
});
我的用户输入总是像“AB1234567”,具有完全相同的字符,但不同的7位数字。
我不熟悉Javascript和Jquery,如果您有更好的方法验证用户输入,请推荐
谢谢。您可以使用下面的模式进行检查
/^AB\d{7}$/
/[A-Za-z0-9]/g
您可以将代码更改为
var pattern = '/^AB\d{7}$/';
if ($userInput.val() == '' || !pattern.test($userInput.val()))
{
alert('Please enter a valid code.');
return false;
}
\d{7}
匹配[0-9]范围内的7位数字您可以按照以下代码执行此操作:
if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
// it is a valid value.
} else {
// show error here
}
希望对您有所帮助。您可以使用下面的正则表达式进行检查
/^AB\d{7}$/
/[A-Za-z0-9]/g
你的代码可能是这样的
var _pattern=/[A-Za-z0-9]/g
if($userInput.val().match(_pattern))
{
//your code goes here..
}
谢谢,试试这个$("#check_data").click(function(){
var $userInput = $('#user_input').val();
var pattern = /^AB[0-9]{7}?/g;
if(!$userInput.match(pattern)){
alert('Please enter a valid code.');
return false;
}
});
那么这个值是AB1234567的模式,但它不是精确的值?听起来你需要使用正则表达式。试试这个模式^AB[0-9]{7}?你需要的模式:[a-zA-Z]{2}[0-9]{7}假设是任意字母max 2任意数字max 7