1

I used another answer to solve my problem.

jQuery.validator.addMethod("greaterThan", function(value, element, params) {
    return new Date(value) > new Date($(params).val());
}, 'Must be greater than {0}.');

However, my date field is a textbox and formatted like dd-mm-yyyy. How do I change this code so that the validation works?

Community
  • 1
  • 1
Can Akaltun
  • 11
  • 1
  • 2

2 Answers2

0
function ValidateEndDate() {
        var startDate = $("txtfromdate").val();
        var endDate = $("txttodate").val();
        if (startDate != '' && endDate !='') {
            if (Date.parse(startDate) > Date.parse(endDate)) {
                $("txttodate").val('');
                alert("Start date should not be greater than end date");
            }
        }
        return false;
    }
Gaushick
  • 31
  • 3
0

You will first have to parse your textbox value to get date from it. Best way would be regular expressions:

Your validator function body should be (explanations in inline comments):

// date parsing regular expression
var rx = /([0-2]?\d|3[01])-(0?\d|1[0-2])-(\d{4})/i;

// get textbox value
var val = $(params).val();

// default date
var date = new Date();

// parse date if entered correctly
if (rx.test(val))
{
    // get date parts
    var result = rx.exec(val);

    // generate date instance
    date = new Date(result[3], result[2]-1, result[1]);
}

// validate dates
return new Date(value) > date;
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404