0

I'm trying to use a custom validation rule with jquery.validator. In the form there are 2 text fields 'startdate' and 'enddate', containing date strings (using jquery.ui datepicker). The date in the 'enddate' field has to be "bigger than" the one in startdate.

I found the following 'greaterThan' custom function in the additional file that comes with validator:

 $.validator.addMethod( "greaterThan", function( value, element, param ) {
            var target = $( param );

            if ( this.settings.onfocusout && target.not( ".validate-greaterThan-blur" ).length ) {
                target.addClass( "validate-greaterThan-blur" ).on( "blur.validate-greaterThan", function() {
                    $( element ).valid();
                } );
            }

            return value > target.val();
        }, "Please enter a greater value." );

Now I'm not sure how to do write the 'rules' part for this field. Thanks for help!! Regards

I tried something like this:

rules {
  enddate:{
      greaterThan: true,
      value: startdate
  }
}

but that doesn't work...

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Shouldn't that be `enddate: { greaterThan: startdate }` – freedomn-m Aug 15 '23 at 12:02
  • Thanks, but i forgot to say theres also a required:true, minLength: 10 rule for the same field. Confused how to set that all... – Andreas74 Aug 15 '23 at 12:13
  • From what I can gleam from other SO questions on [tag:jquery-validate], it's a case of `field : { rule: params, rule: params, rule: params }` - so would be `enddate: { required: true, minLength: 10, greaterThan: startdate }` – freedomn-m Aug 15 '23 at 12:16
  • Thanks, but that doesn't seem to work. Since the datefields are in the format 2023-08-23 i probably have to get rid of the dashes and cast it to an int for the compare to work ? – Andreas74 Aug 15 '23 at 12:35
  • Hm, very strange behaviour. When i use the jquery-ui datepickler, the required and minlength setting don't work. When i manually type into the fields then they work. The greaterThan rule does not work at all. – Andreas74 Aug 15 '23 at 13:01
  • If you want to compare dates, then you need to convert to dates to compare. If you convert "2023-12-13" to an int, it would be `2023`. If they're in ansi format (y-m-d) then string comparison will work fine. – freedomn-m Aug 15 '23 at 14:50
  • Please take a look to this: https://stackoverflow.com/questions/833997/validate-that-end-date-is-greater-than-start-date-with-jquery – jcarrera Aug 15 '23 at 15:28
  • Please use the SO search function. This has been asked and answered many times. – Sparky Aug 15 '23 at 21:41

0 Answers0