Wednesday, May 23, 2012

Date field validation in Jquery using Jquery.validate.js and Date.js
Pre-requisites
  1. Jquery.Validate.js
  2. Date.js
Note: - The below solution is selecting all date fields by looking for the string "datepicker" in the "data-bind" attribute.
Solution
function validateAllDateFields() {
    jQuery.validator.addMethod("myDate", function (value, element) {        
        if (value.indexOf("_") >= 0 || value == "") {
            return true;
        }
        return Date.parse(value, "mm/dd/yyyy");
    },
        " Please enter a valid date"
    );

    $('input[type=text]').each(function (c) {
        var databindAttr = $(this).attr("data-bind");
        if (databindAttr != null) {
            if (databindAttr.indexOf("datepicker") >= 0) {
                $(this).addClass("myDate");
            }
        }
    });

    $('form').validate({
        errorPlacement: function (error, element) {
            var nextElement = element.next();
            if (nextElement != null) {
                error.insertAfter(nextElement);
            }
        }

    });
}

No comments:

Post a Comment