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