how to validate Date of birth with three textbox of date month year by jquery validator

后端 未结 4 1932
情深已故
情深已故 2021-01-16 08:36

I need to validate date of birth by using jquery validator with three separate textbox for day month and year.

How to do this please help.

HTML code

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-16 08:40

    You should create a custom validation method for this, along with using the groups option that validate provides:

    /* Custom validation method to validate a date based on several fields: */
    $.validator.addMethod("datemultiple", function(value, element, params) {
        var daySelector = params[0],
            monthSelector = params[1],
            yearSelector = params[2],
            day = parseInt($(daySelector).val(), 10),
            month = parseInt($(monthSelector).val(), 10),
            year = parseInt($(yearSelector).val(), 10),
            dateEntered = new Date(year, month - 1, day);
    
        return this.optional(element) || !isNaN(dateEntered.valueOf());
    
    }, "Please enter a valid date");
    
    $(document).ready(function() {
        $("#myform").validate({
            groups: {
                /* Only display one validation message for day, month, and year: */
                dateOfBirth: "dob-day dob-month dob-year"
            },
            rules: {
                'dob-day': {
                    required: true,
                    datemultiple: ["#dob-day", "#dob-month", "#dob-year"]
                },
                'dob-month': {
                    required: true
                }
            },
            /* Place error messages after the "year" field */
            errorPlacement: function ($error, $element) {
                if ($element.data("fieldgroup") === "dob") {
                    $error.insertAfter("#dob-year");
                }
            }
        });
    });
    

    Example: http://jsfiddle.net/xHC86/

提交回复
热议问题