admin管理员组文章数量:1405603
I'm using a jQuery validation-plugin to validate a form's fields. I've got a scenario where we need to validate a field to allow only mas and numbers.
Here's my HTML-code:
<input type="text" placeholder="Number of Employees" required class="form-control" name="employeeno">
And here are the jQuery validation-plugin rules:
employeeno:{
Regex: "[0-9,]+",
minlength: 1,
maxlength: 20
},
jQuery.validator.addMethod("Regex", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
}, "Please enter a valid number");
This code actually works if I type at least 2 characters. But if I'm entering only one number - e.g. 2 or 3 - it is displaying an error, allthough I've set my minimum length to one. Why?
I'm using a jQuery validation-plugin to validate a form's fields. I've got a scenario where we need to validate a field to allow only mas and numbers.
Here's my HTML-code:
<input type="text" placeholder="Number of Employees" required class="form-control" name="employeeno">
And here are the jQuery validation-plugin rules:
employeeno:{
Regex: "[0-9,]+",
minlength: 1,
maxlength: 20
},
jQuery.validator.addMethod("Regex", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
}, "Please enter a valid number");
This code actually works if I type at least 2 characters. But if I'm entering only one number - e.g. 2 or 3 - it is displaying an error, allthough I've set my minimum length to one. Why?
Share Improve this question edited Aug 17, 2015 at 12:01 Stephan Weinhold 1,6411 gold badge28 silver badges37 bronze badges asked Aug 17, 2015 at 11:23 user3289108user3289108 7705 gold badges10 silver badges29 bronze badges1 Answer
Reset to default 4Your regex is not correct. .
in regex matches any one character, you need to use ^
for start of the line
return value.match(new RegExp("^" + param + "$"));
^^ here
But you can use the pattern rule from the additional methods file
rules: {
employeeno: {
pattern: /^[0-9,]+$/,
minlength: 1,
maxlength: 20
}
},
messages: {
employeeno: {
pattern: 'Please enter a valid number'
}
}
Demo: Fiddle
本文标签: javascriptAllow numbers and commas in JQuery ValidationStack Overflow
版权声明:本文标题:javascript - Allow numbers and commas in JQuery Validation? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744294043a2599255.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论