Reputation: 770
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 commas 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?
Upvotes: 4
Views: 12077
Reputation: 388366
Your 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
Upvotes: 4