jQuery validate: How to add a rule for regular expression validation?

jquery regular expression validation for password
jquery regular expression validation for number
jquery regular expression validation for name
jquery regular expression validation for special characters
jquery validate rules
jquery validate pattern
jquery regex
jquery validate custom rule

I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:

$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })

How do I add a custom rule to achieve this?

Thanks to the answer of redsquare I added a method like this:

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);

now all you need to do to validate against any regex is this:

$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })

Additionally, it looks like there is a file called additional-methods.js that contains the method "pattern", which can be a RegExp when created using the method without quotes.


Edit

The pattern function is now the preferred way to do this, making the example:

 $("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js

Form validation with jQuery Validate, I do a validation for a textbox (email field), with help from the validate from the jQuery Validation plugin $("input[title='Email']").rules( "add", I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expr

You can use the addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

Validate a textfield and use regex, validator.addMethod(). Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based� jquery validate rules (8) I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:

I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
    <script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">

        $().ready(function() {
            $.validator.addMethod("EMAIL", function(value, element) {
                return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
            }, "Email Address is invalid: Please enter a valid email address.");

            $.validator.addMethod("PASSWORD",function(value,element){
                return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
            },"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");

            $.validator.addMethod("SUBMIT",function(value,element){
                return this.optional(element) || /[^ ]/i.test(value);
            },"You did not click the submit button.");

            // Validate signup form on keyup and submit
            $("#LOGIN").validate({
                rules: {
                    EMAIL: "required EMAIL",
                    PASSWORD: "required PASSWORD",
                    SUBMIT: "required SUBMIT",
                },
            });
        });
    </script>
</head>
<body>
    <div id="LOGIN_FORM" class="form">
        <form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
            <h1>Log In</h1>
            <div id="LOGIN_EMAIL">
                <label for="EMAIL">Email Address</label>
                <input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
            </div>
            <div id="LOGIN_PASSWORD">
                <label for="PASSWORD">Password</label>
                <input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
            </div>
            <div id="LOGIN_SUBMIT">
                <input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
            </div>
        </form>
    </div>
</body>
</html>

regex | Search Results, Description: Add a custom validation method. In general, it is a good idea to encapsulate those regular expressions inside their own method. A Regular Expression is simply a pattern for a set of values. You can use a regular expression as a rule, to identify a string value. For example, if an expected field, must contain the string ‘abc’, the regular expression for the field is “/abc/”. To create regular expressions for form fields such as name, email id and the contact

No reason to define the regex as a string.

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var check = false;
        return this.optional(element) || regexp.test(value);
    },
    "Please check your input."
);

and

telephone: { required: true, regex : /^[\d\s]+$/, minlength: 5 },

tis better this way, no?

jQuery.validator.addMethod(), Add real time client side validation for form fields using regular use fixed strings to validate results, because let's face it, there are no fixed set of names You can use a regular expression as a rule, to identify a string value. In this tutorial we will learn how to use the jQuery validate plugin to validate our forms, how to define our personal message, etc

Extending PeterTheNiceGuy's answer a bit:

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            if (regexp.constructor != RegExp)
                regexp = new RegExp(regexp);
            else if (regexp.global)
                regexp.lastIndex = 0;
            return this.optional(element) || regexp.test(value);
        },
        "Please check your input."
);

This would allow you to pass a regex object to the rule.

$("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });

Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.

Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:

$("password").rules("add", {
    regex: [
        /^[a-zA-Z'.\s]{8,40}$/,
        /^.*[a-z].*$/,
        /^.*[A-Z].*$/,
        /^.*[0-9].*$/
    ],
    '!regex': /password|123/
});

But implementing those would maybe be too much.

Real Time Form Validation using Regular Expressions in jQuery, The jQuery Validation plugin; Adding validation rules; By calling the addMethod function of the validator, you can define your own rules to be applied Regular expressions are defined as strings of characters that must be matched literally� Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message. jQuery.validator.addMethod( name, method [, message ] )

Chapter 14. Creating validation rules, Contribute to jquery-validation/jquery-validation development by creating an account on Then select a form to validate and call the validate method. For more information on how to setup a rules and customizations, check the documentation. As of version 1.12.0 this plugin is using the same regular expression that the� In jQuery, is there a function/plugin which I can use to match a given regular expression in a string? For example, in an email input box, I get an email address, and want to see if it is in the correct format. What jQuery function should I use to see if my validating regular expression matches the input?

jquery-validation/jquery-validation, How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex? For example, what the rule name is all lowercase. This is because the jQuery validation function dataRules applies . For jquery validation i need regex for SSN number format and EIN number format. jQuery validate: How to add a rule for regular expression validation? 1524.

javascript - jQuery Validate Plugin, Adding validation to your forms with JQuery gives you a lot of flexibility as you can add more rules and conditions to your validation and you can addMethod to check if the e-mail is valid by checking its format using regular expression. Next� Regular expressions offer an extremely flexible and powerful way of adding validation to your website forms. Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements.

Comments
  • Please say you're checking the input server side and not just relying on client side validation as this can obviously be turned off.
  • of course! :-) Validation on the server is a must
  • OMG it DOESN'T have regex validation?!
  • I mean, who'd want regex for validation anyway... ... ;)
  • $("Textbox") should be $("#Textbox").
  • I would have let the RegExp be defined outside the method as a literal, instead of the invocation from a string..
  • this is super useful and should be included in jquery :(
  • Or add it to validator like this: ... rules: { textbox_input_name_attr: { required: true, regex: "^[a-zA-Z'.\\s]{1,50}$" } }, ....
  • You enter a custom message like this: $('#element').rules('add', { regex: /[abc]/, messages { regex: "custom message' }});
  • Don't really answer the question. What if you want a general regex rule? With this answer you would have to addMethod for each diffrent regex.