How can I validate that the max field is greater than the min field?

后端 未结 2 1568
耶瑟儿~
耶瑟儿~ 2021-01-02 05:26

I have a few sets of min and max fields in a form, where the user can specify a range by filling in a min and a max. I\'m using jQuery\'s Validate plugin for my form validat

2条回答
  •  感情败类
    2021-01-02 06:02

    Simple and good way to use addmethod

    $.validator.addMethod("greaterThan",
    
    function (value, element, param) {
      var $min = $(param);
      if (this.settings.onfocusout) {
        $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
          $(element).valid();
        });
      }
      return parseInt(value) > parseInt($min.val());
    }, "Must be greater than to field 1");
    

    validating code

    filed2_name: {
    
                greaterThan: '#filed1_id'
            },  
    

    second i prefer first

    $.validator.addMethod('le', function(value, element, param) {
          return this.optional(element) || value <= $(param).val();
    }, 'Invalid value');
    $.validator.addMethod('ge', function(value, element, param) {
          return this.optional(element) || value >= $(param).val();
    }, 'Invalid value');
    
    $('form').validate({rules: {
                fieldName1: {le: '#fieldID2'},
                fieldName2: {ge: '#fieldID1'},
                 ...
          },
          messages: {
                fieldName1: {le: 'Must be less than or equal to field 2'},
                fieldName2: {ge: 'Must be greater than or equal to field 1'},
                ...
          }
    });
    

提交回复
热议问题