Jquery validation one rule fails should not jump to another rule

后端 未结 1 1427
眼角桃花
眼角桃花 2021-01-16 20:58

I am using jquery validation, I have to implement functionality so that if any rule fails the form should not submit. The work is done validation working fine.

The p

相关标签:
1条回答
  • 2021-01-16 21:38

    You can use the custom error handler showErrors, where you only set the first found error in the error list:

    showErrors: function(errorMap, errorList) {
        if (errorList.length) {
           this.errorList = [errorList[0]];
        }
    
        this.defaultShowErrors();
      }
    

    The error list needs to be an array, so that's why the first error is placed inside the [], which defines an array.

    So in total you get:

    $("#myform").validate({
      rules: {
        fname: "required",
        lname: "required",
        fromDate: "required",
        endDate: "required"
      },
      showErrors: function(errorMap, errorList) {
        if (errorList.length) {
           this.errorList = [errorList[0]];
        }
    
        this.defaultShowErrors();
      }
    });
    

    JsFiddle


    Now, if you want the internal validation check stop at its first error. So not only visually not showing the errors, but actually stopping checking once one field is falsy. You can overwrite the internal check function checkForm().

    I will simply check if the element is true or false, once false I know at least one field is falsy. So I break the check loop:

    validator.checkForm = function() {
      this.prepareForm();
      for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
        if (!this.check(elements[i]))
          return false;
      }
      return this.valid();
    };
    

    JsFiddle

    Now I want to mind you I am not the creator of this plugin, so I do not fully know if this works accordingly. I would suggest to write your own validation code, to have full control on what you are doing.

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