Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the jquery validation plugin, how can I add a regex validation on a textbox?

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.

like image 943
mrblah Avatar asked Jun 27 '09 21:06

mrblah


People also ask

How do you validate a form in regex?

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

What is jQuery validation plugin?

jQuery Validation Plugin It lets you specify custom validation rules using HTML5 attributes or JavaScript objects. It also has a lot of default rules implemented and offers an API to easily create rules yourself.

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

How we can use jQuery validation plugins in MVC?

The jQuery validation plugin leverages a CSS selector like syntax to apply a set of validation rules. You can download the plugin (js) file from jQuery website. The password and confirm password objects are matched by the validation plugin for you and shows the message on the equalTo attribute if they don't match.


2 Answers

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"
            }
        }
    });
});
like image 141
natacado Avatar answered Sep 18 '22 12:09

natacado


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");
}
like image 29
karim79 Avatar answered Sep 16 '22 12:09

karim79