Grateful
Grateful

Reputation: 10205

jQuery.validator.addMethod and required vs optional

For the following code,

jQuery.validator.addMethod
(
      "exactlength",

      function(value, element, param) 
      {
           return this.optional(element) || value.length == param;
      },

      jQuery.format("Please enter exactly {0} characters.")
);

I understand that

but I don't quite understand why this.optional(element) || has been included for a required field. Most of the examples that I have seen for addMethod seem to have this part of the clause. But why is it compulsory, even for the fields that are required.

Secondly, let's suppose I wanted email validation, I would add something like,

email: 
{
    required: true,
    email: true,
},

I would also add the following,

jQuery.validator.addMethod
(
      "minLengthID",

      function(value, element, param) 
      {
           return this.optional(element) || value.length >= param;
      },

      jQuery.format("Please enter more than {0} characters.")
);


jQuery.validator.addMethod
(
      "maxLengthID",

      function(value, element, param) 
      {
           return this.optional(element) || value.length <= param;
      },

      jQuery.format("Please enter less than {0} characters.")
);

but I don't understand why this.optional(element) || is necessary here. I would appreciate any directions.

Upvotes: 0

Views: 3264

Answers (1)

Sparky
Sparky

Reputation: 98738

Firstly, minlength and maxlength work perfectly fine with the email rule.

$('#myform').validate({
    rules: {
        emailaddress: {
            required: true,
            email: true,
            minlength: 6,
            maxlength: 30
        }
    }
});

DEMO: http://jsfiddle.net/arex5q69/

Notice however, that you'll need to satisfy the email rule before the minlength and maxlength rules are evaluated. Also notice that a very short email address [email protected] is six characters long so your minlength: 6 rule is satisfied immediately.

Conversely, if you put the minlength and maxlength rules before the email rule, then they will be evaluated first.

$('#myform').validate({
    rules: {
        emailaddress: {
            required: true,
            minlength: 6,
            maxlength: 30,
            email: true
        }
    }
});

DEMO 2: http://jsfiddle.net/arex5q69/1/


this.optional(element) || as part of your custom rule simply makes your field optional when this rule is used alone.

However, when you combine your "optional" custom rule with a required: true, it's a moot point since the field would never be optional.

The reason you would put this.optional(element) || in your custom rule, is that it leaves you the ability to use it on fields both with and without the required rule.

Otherwise, if you leave out this.optional(element) ||, your custom rule will always make the field required even when you might not want the field required.

Upvotes: 2

Related Questions