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.

1

2 Answers 2

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"
            }
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 - 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
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");
}

1 Comment

@karmin79: Thanks for elegant solution. Just minor thing you are missing one ")" before "{".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.