Validate that end date is greater than start date with jQuery

前端 未结 15 1962
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:14

How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?

15条回答
  •  误落风尘
    2020-11-22 13:30

    I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date constructor, but others will not. For example, Chrome 18 gives

    > new Date("66")
      Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)
    

    This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11") is greater than new Date("66") and this is obviously the opposite of the desired effect).

    Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().

    In the end, the code becomes:

    $.validator.addMethod(
        "greaterThan",
        function(value, element, params) {
            var target = $(params).val();
            var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
            var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
            if (isValueNumeric && isTargetNumeric) {
                return Number(value) > Number(target);
            }
    
            if (!/Invalid|NaN/.test(new Date(value))) {
                return new Date(value) > new Date(target);
            }
    
            return false;
        },
        'Must be greater than {0}.');
    

提交回复
热议问题