Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

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

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

I wonder what this.optional(element) does. I created two forms to test:
Form1 and Form2 — one with this.optional(element) and the other without it. Theoretically speaking and according to a couple of comments on this answer by Andrew Whitaker:

all this.optional does is say "if the field is optional, return true if it is blank"

and

The this.optional check is basically checking to see if the field is blank or not before evaluating whether or not it meets the rule.

But in action I see no difference in how Form1 and Form2 work. Please help me understand the difference in action.

question from:https://stackoverflow.com/questions/13093971/what-does-this-optionalelement-do-when-adding-a-jquery-validation-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...