How can I check for exact length using jQuery Validation?

狂风中的少年 提交于 2019-12-31 17:53:39

问题


Using the jQuery Validation plugin to validate forms, how would you confirm that a string is exactly X characters long?


回答1:


Since there is (currently) no built-in method for this, you'd need to add your own method. This would work:

jQuery.validator.addMethod("exactlength", function(value, element, param) {
 return this.optional(element) || value.length == param;
}, $.validator.format("Please enter exactly {0} characters."));

Which could then be used like this:

$("#formtovalidate").validate({
  rules: {
    somefield: {
      exactlength: 10
    }
   });

Update - How it Works

I've been asked how this works. I don't know all the details; I modeled this method on previously existing ones. However, this is my best attempt to explain it.

  • The function takes in value, element, and param.
    • value is the value entered in the field being validated
    • element is the field itself
    • param is whatever comes after the rule type and colon. In the example above, it's the 10 in exactlength: 10
  • The next line is a return statement. This will give the final verdict of the validation method back to the code that called it. Any validation method that returns true is saying 'this field passes validation!' It will return the value of the line it's on.
  • The return is followed by two declarations, separated by an 'or' operator (||).
    • The || operator means 'evaluate the item left of this. If it's true, return true. If not, try the one on the right. If it's true, return true. Otherwise, return false.'
      • The item on the left is this.optional(element). If the element is not required in your rules, this will return true, and so will the validation. Which means 'If I don't tell you that this field is required, I don't care whether it validates.'
      • If the field is required, we move to the right side of the ||. This is the actual validation test. It compares the length of the field's input with the length you specified it should be. If they are the same, it returns true, the method returns true, and validation passes. Otherwise, validation fails.

That's about it. For further help, see the documentation, particularly the part about custom validation methods.




回答2:


example:

rules : {
"someFieldName":{digits:true,minlength:20,maxlength:20}
}



回答3:


The easiest way is to use the existing validation methods via data attributes, then just set your own validation message for clarity.

<input data-rule-minlength="8" data-rule-maxlength="8" data-msg-minlength="Exactly 8 characters please" data-msg-maxlength="Exactly 8 characters please">



回答4:


You could also make the existing rangelength method support exact range by supplying a dynamic message like this:

$.extend($.validator.messages, {
    rangelength: function(args, inputElement) {
        var isExactRange, min, max;

        // Cast arguments as numbers
        min = Number(args[0]);
        max = Number(args[1]);

        isExactRange = min === max;

        if (isExactRange) {
            return 'Please enter exactly ' + min + ' characters.';
        }


        return 'Please enter between ' + min + ' and ' + max + ' characters.';
    }
);

As can be seen, you can generate messages on the fly based on the arguments passed to the validation methods. Message callbacks are passed the validation method arguments as their first argument, and the input element being validated as their second argument.

This makes it possible to return one message when a exact range is specified, but another if upper and lower bounds are not the same.

To fallback to the default rangelength message, replace

'Please enter between ' + min + ' and ' + max + ' characters.'

with

$.validator.messages.rangelength

It would be nice if the official documentation would be updated, as it is difficult to navigate in and does not describe all functionalities of the plugin.



来源:https://stackoverflow.com/questions/1229141/how-can-i-check-for-exact-length-using-jquery-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!