简体   繁体   中英

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"
                    }
                });

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM