using the jquery validation plugin, how can I add a regex validation on a textbox?
Solution 1
Define a new validation function, and use it in the rules for the field you want to validate:
$(function ()
{
$.validator.addMethod("loginRegex", function(value, element) {
return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
}, "Username must contain only letters, numbers, or dashes.");
$("#signupForm").validate({
rules: {
"login": {
required: true,
loginRegex: true,
}
},
messages: {
"login": {
required: "You must enter a login name",
loginRegex: "Login format not valid"
}
}
});
});
Solution 2
Not familiar with jQuery validation plugin, but something like this should do the trick:
var alNumRegex = /^([a-zA-Z0-9]+)$/; //only letters and numbers
if(alNumRegex.test($('#myTextbox').val())) {
alert("value of myTextbox is an alphanumeric string");
}
mrblah
test testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest test asdf asdf
Updated on March 29, 2020Comments
-
mrblah about 4 years
I am using the jquery validation plugin from: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
How can I add a regex check on a particular textbox?
I want to check to make sure the input is alphanumeric.
-
Alistair over 13 yearsNote: the addmethod doesn't need to go in document.ready, may as well load it immediately to free up document.ready for stuff that needs to go there.
-
Arman about 13 years@karmin79: Thanks for elegant solution. Just minor thing you are missing one ")" before "{".
-
Cofey about 13 yearsWhat would need to be changed in order to display a specific error message if the value is not alphanumeric and another if it isn't between the min/max length?
-
natacado about 13 years@Cofey - I didn't actually validate (pun intended) that this works, but I updated the example to use custom error messages using the documentation at docs.jquery.com/Plugins/Validation/validate#options