4b0
4b0

Reputation: 22323

Compare Dates using validate.js

in jquery i try to validate my page.I have to filds txtStartDate and txtEndDate.i want to validate start date is lower than end date.How this condition append in given code.Bcz txtPageName and txtTitle is already validate.Thanks.

                 var v = $("#form1").validate({
                    ignore: ':hidden',
                    rules: {
                        : { required: true },
                        txtTitle: { required: true }


                    },
                    messages: {
                        txtPageName: "<br/>Please enter a Page Name",
                        txtTitle: "<br/>Please enter a Title"
                    }
                });

Upvotes: 0

Views: 9660

Answers (1)

Sandeep
Sandeep

Reputation: 819

You can need a custom rule for doing this. See the below code: isAfterStartDate checks is start date if less than end date and returns a boolean. This is used by the custom validation rule to validate the txtEndDate.

var isAfterStartDate = function(startDateStr, endDateStr) {
            var inDate = new Date(startDateStr),
                eDate = new Date(endDateStr);

            if(inDate < eDate) {
                return false;
            }

        };
jQuery.validator.addMethod("isAfterStartDate", function(value, element) {

        return isAfterStartDate($('#txtStartDate').val(), value);
    }, "End date should be after start date");

 var v = $("#form1").validate({
                ignore: ':hidden',
                rules: {
                    txtPageName: { required: true },
                    txtTitle: { required: true },
                    txtStartDate : {required: true}
                    txtEndDate: {
                                  required: true,
                                  isAfterStartDate: true
                                 }


                },
                messages: {
                    txtPageName: "<br/>Please enter a Page Name",
                    txtTitle: "<br/>Please enter a Title"
                }
            });

This works assuming the date is format "dd/mm/yyyy".

Upvotes: 3

Related Questions