User Tools

Site Tools


js:jquery_validate_date

Validate a date in format dd-mm-YYYY

23.01.2010

We're using validation jquery plugin.
To check a date in our desired format, add a new method like this (the function also check for date validity, not only the format - 30/30/3030 will return false):

    $.validator.addMethod(
        "roDate",
        function(value, element) {
            var check = false;
            var re = /^\d{1,2}-\d{1,2}-\d{4}$/;
            if( re.test(value)) {
                var adata = value.split('-');
                var gg = parseInt(adata[0],10);
                var mm = parseInt(adata[1],10);
                var aaaa = parseInt(adata[2],10);
                var xdata = new Date(aaaa,mm-1,gg);
                if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) ) {
                        check = true;
                } else {
                        check = false;
                }
            } else
                    check = false;
            return this.optional(element) || check;
        }, 
        "Date required in dd-mm-yyyy format"
    );

And check it like this:

    $("#form_id").validate({ 
        rules: { 
             date_field: { required: true, roDate: true }
        },
        messages: { 
             date_field: "Your custom error message", 
        }
    });

js/jquery_validate_date.txt · Last modified: 2013/03/16 17:40 (external edit)