1

I have three fields in my form: status, ask date, and expected date

If my Status=A, I would like my expected date to be required in validation additionally I would like my expected date validated to always be greater than the ask date

so here are my rules

rules: {
      status: {
        required: true,
      },
      ask_date: {
        required: true,
        date:true,
      },
      expected_date: {

        required: function(element){
            if($('#status').val()=='A'){
              return true;
            } else {
              return false;
            }
        },

        greaterThan: "#ask_date",
        date:true,
      },

How can I say invoke the greaterThan method ONLY when the field meets the conditions for being required?

the "greaterThan" is custom jquery validation method i am using for this from a separate stack overflow here Validate that end date is greater than start date with jQuery

jQuery.validator.addMethod("greaterThan", 
function(value, element, params) {

    if (!/Invalid|NaN/.test(new Date(value))) {
        return new Date(value) > new Date($(params).val());
    }

    return isNaN(value) && isNaN($(params).val()) 
        || (Number(value) > Number($(params).val())); 
},'Must be greater than {0}.');
Community
  • 1
  • 1
Jay Rizzi
  • 4,196
  • 5
  • 42
  • 71

1 Answers1

1

"How can I say invoke the greaterThan method ONLY when the field meets the required conditions?"

Since the field is only required under those conditions, ideally, none of your other rules should be fired when the field is left blank. However, there is a piece missing from your custom method that would allow it to be ignored whenever the field is left blank.

Testing against the condition, this.optional(element), will ensure that your custom rule is not enforced on a blank field.

jQuery.validator.addMethod("greaterThan", function(value, element, params) {
    if (this.optional(element)) {  // "required" not in force and field is empty
        return true;
    } else {  // otherwise, use your rule
        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date($(params).val());
        }
        return isNaN(value) && isNaN($(params).val()) || (Number(value) > Number($(params).val()));
    }
},'Must be greater than {0}.');
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • @whoami, you have enough reputation to already know that we are not allowed to ask/answer questions from within comments. – Sparky Jun 01 '18 at 16:21