What does this.optional(element) do when adding a jQuery validation method?

前端 未结 2 1338
遥遥无期
遥遥无期 2020-12-30 19:06

Please see the documentation:
https://jqueryvalidation.org/jQuery.validator.addMethod/

I wonder what this.optional(element) does. I created two fo

相关标签:
2条回答
  • 2020-12-30 19:47

    OK... so in your examples, the field is never blank in either form. Either it has a placeholder value, or an attempt at an email address. The whole point of this.optional(element) is to immediately return true if the element is blank AND it is not required.

    So if you had these two methods:

    jQuery.validator.addMethod("BOB", function (value, element) {
        return this.optional(element) || 
            element.value === 'BOB';
    }, 'You did not enter BOB');
    
    jQuery.validator.addMethod("mustbeBOB", function (value, element) {
        return element.value === 'BOB';
    }, 'You did not enter BOB');
    

    Adding a class of BOB required would be the same as entering a class of mustbeBOB. Compare that to having a class of BOB which would allow for a blank or "BOB", vs a class of mustbeBOB which will only pass validation with a value of BOB, blank would fail. Does that make more sense?

    0 讨论(0)
  • 2020-12-30 19:58

    this.optional is intended to be used in general-purpose validation methods, which might be used with required or optional elements. It allows them to skip all their own checks if the field is not filled in. If the field is optional and blank, the method calling this.optional returns successfully immediately.

    By using this, the method can assume that the value is non-empty, which can simplify the rest of its coding.

    0 讨论(0)
提交回复
热议问题