16

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.

mrblah
  • 99,669
  • 140
  • 310
  • 420
  • There are lots of additional methods plugins here http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – dstonek Nov 26 '11 at 21:18

2 Answers2

35

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"
            }
        }
    });
});
natacado
  • 6,697
  • 1
  • 19
  • 8
  • Note: 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. – Alistair Nov 15 '10 at 23:39
  • What 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? – Cofey Apr 12 '11 at 01:43
  • @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 http://docs.jquery.com/Plugins/Validation/validate#options – natacado Apr 12 '11 at 17:05
7

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");
}
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 1
    @karmin79: Thanks for elegant solution. Just minor thing you are missing one ")" before "{". – Arman Feb 22 '11 at 08:07