Friday, May 11, 2012

More jQuery validation shenanigans

Here's my latest custom rule for doing regex within jQuery validation. Lifted & modified from stack overflow.  Not doing a whole lot, but super useful:


/*
* Malachi Burke.  
* (c) 2012 Apprentice Lib
*/
// http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation
$.validator.addMethod(
        "regex",
        function (value, element, regexp) {
            var options = "";
            if (typeof (regexp) != "string") {
                options = regexp.options;
                regexp = regexp.match;
            }
            var re = new RegExp(regexp, options);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);
Using it is like:
fieldName: { required: true, regex: { match: "your regex string" } }