0

I want to compare two date fields using Foolproof validation where the second field must be greater than the first field. However, both can be null. Even when using PassOnNull = True, the validation fails when both fields are null. This works as expected using [GreaterThanOrEqualTo], but my second date must be greater.

[GreaterThan("DateFrom", PassOnNull = true, ErrorMessage = "Date To must be greater than Date From")]
public DateTime? DateTo { get; set; }

In looking at the source, it bypasses validation when either field is null (but not both). Is there any reasoning behind this? This doesn't really make sense to me. I can easily change the source, but being a NuGet install, I'm at the mercy of it being overwritten. Otherwise, I can just include it manually and be done. Here is the source snippet:

    if (passOnNull) {

        var isNullish = function (input) {
            return input == null || input == undefined || input == "";
        };

        var value1nullish = isNullish(value1);
        var value2nullish = isNullish(value2);

        if ((value1nullish && !value2nullish) || (value2nullish && !value1nullish))
            return true;
    }

The following modification makes more sense to me in almost any scenario I can think of since required fields would still have their own validation to pass:

        if (value1nullish || value2nullish)
            return true;

Is there another way I should be validating this, or is FoolProof just needing a fix?

Jason Butera
  • 2,376
  • 3
  • 29
  • 46

1 Answers1

0

You can utilize .change() event, Array.prototype.every() , .eq(), .valueAsDate property of input type="date" , required attribute at both input type="date" elements

var dates = $("input[type=date]");

dates.change(function(e) {
  if (dates.get().every(function(el) {
        return el.valueAsDate !== null
      }) 
      && dates.eq(1)[0].valueAsDate > dates.eq(0)[0].valueAsDate) {
        alert(true)
  } else {
      alert(false)
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form>
  <input type="date" name="date1" required />
  <input type="date" name="date2" required />
  <input type="submit" />
</form>
guest271314
  • 1
  • 15
  • 104
  • 177