2

I have 3 validator methods to validate a form field. For each form field I have to validate, I needed to call these 3 validators all the time. Is it possible to write one validator method, that internally calls these 3 methods and returns the appropriate error?

/*
 * Do not allow a name to include only underscores.
 */
jQuery.validator.addMethod('notallunderscores', function(value, element)
{
    value = value.replace(/\_/g,'');
    return this.optional(element) || value.length > 0;
}, "Enter more than only underscore characters.");

/*
 * Do not allow a name to include only hyphens.
 */
jQuery.validator.addMethod('notallhyphens', function(value, element)
{
    value = value.replace(/\-/g,'');
    return this.optional(element) || value.length > 0;
}, "Enter more than only hyphens.");

/*
 * Do not allow a name to include leading or trailing spaces.
 */
jQuery.validator.addMethod('notrailingorleadingspaces', function(value, element)
{
    return this.optional(element) || ! value.match(/^ .*|.*\ $/g);
}, "Please remove any leading or trailing spaces.");

The validator I am looking for should be like this:

     /*
     * Call each of the above validator methods and return appropriate error.
     */
    jQuery.validator.addMethod('validateformfield', function(value, element)
    {
        //Call the above 3 validator methods
        //Return the appropriate error returned by the above validators.
    }, "Return the error message from the failed validator.");
Jake
  • 25,479
  • 31
  • 107
  • 168

1 Answers1

3

No, you cannot combine three different custom methods into a single custom method while also maintaining three different error messages. There is not a way to nest them into each other.


However, you can make a "compound rule" and assign it to a class using the addClassRules method.

jQuery.validator.addClassRules("myCompoundRule", {
    notallunderscores: true,
    notallhyphens: true,
    notrailingorleadingspaces: true
});

Then you assign the class to the input where you want these rules to apply...

<input type="text" name="foo" class="myCompoundRule ...

Otherwise, if you don't want to use a class, then you must declare the custom rules individually using the .validate() method, as I presume you're already doing...

$('#myform').validate({
    rules: {
        foo: {
            notallunderscores: true,
            notallhyphens: true,
            notrailingorleadingspaces: true
        }
    }
});

You could also combine various rules into "sets". See my SO answers below for other creative ways to assign multiple rules to multiple fields.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285