javascript 如何通过jquery验证器使用日期月份年份的三个文本框验证出生日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11009976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:47:50  来源:igfitidea点击:

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

javascriptjquery-validate

提问by user617204

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

我需要使用 jquery 验证器和三个单独的文本框来验证出生日期,分别代表日月和年。

How to do this please help.

如何做到这一点,请帮助。

HTML code

HTML代码

<input type="text" maxlength="2" placeholder="DD" class="dob-day  fillone" name="dob-day" id="dob-day" data-fieldgroup="dob" data-fillone-field="true" />
<input type="text" maxlength="2" placeholder="MM" id="dob-month" class="dob-month fillone" data-fieldgroup="dob" data-fillone-field="true">
<input type="text" maxlength="4" placeholder="YYYY" class="dob-year fillone" id="dob-year" data-fieldgroup="dob" data-fillone-field="true">

I am using data-group for grouping the textbox

我正在使用数据组对文本框进行分组

回答by Andrew Whitaker

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

您应该为此创建一个自定义验证方法,并使用groups验证提供的 选项:

/* 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/

示例:http : //jsfiddle.net/xHC86/

回答by David East

I wrote a Javascript module that handles whether or not the data is valid, you can check out a full working example in the JSFiddle link.

我编写了一个 Javascript 模块来处理数据是否有效,您可以在 JSFiddle 链接中查看完整的工作示例。

http://jsfiddle.net/dceast/vmHjN/

http://jsfiddle.net/dceast/vmHjN/

Here is the module that does the validation:

这是进行验证的模块:

var compareDate, checkDates = false;
var validateObject = {
    init: function(year, month, day) {
        return this.compareDate.init(year, month, day);
    },
    compareDate: {
        init: function(year, month, day) {
            var isValid = false;
            // Compensate for zero based index, if month was not
            // subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
            month -= 1;

            // Create a new date object with the selected
            // year, month, and day values and retrieve the
            // milliseconds from it.
            var mSeconds = (new Date(year, month, day)).getTime();
            var objDate = new Date();

            // Set the time of the object to the milliseconds 
            // retrieved from the original date. This will
            // convert it to a valid date.
            objDate.setTime(mSeconds);

            // Compare if the date has changed, if it has then
            // the date is not valid 
            if (objDate.getFullYear() === year &&
                objDate.getMonth() === month &&
                objDate.getDate() === day) 
            {
                isValid = true;
            }
            return isValid;
        }
    }
};

回答by Vuong

sorry, i'm cannot speak english

对不起,我不会说英语

you can check date < 30 or 31 respectively month month < 12 year ...

您可以分别检查日期 < 30 或 31 月 月 < 12 年...

i think it's easy when you used three textbox :( just js

我认为当你使用三个文本框时很容易:( 只是 js

回答by Kishore Dhanekula

var compareDate, checkDates = false;
var validateObject = {
    init: function(year, month, day) {
        return this.compareDate.init(year, month, day);
    },
    compareDate: {
        init: function(year, month, day) {
            var isValid = false;
            // Compensate for zero based index, if month was not
            // subtracted from one 0 === Jan, 1 === Feb, 2 === Mar
            month -= 1;

            // Create a new date object with the selected
            // year, month, and day values and retrieve the
            // milliseconds from it.
            var mSeconds = (new Date(year, month, day)).getTime();
            var objDate = new Date();

            // Set the time of the object to the milliseconds
            // retrieved from the original date. This will
            // convert it to a valid date.
            objDate.setTime(mSeconds);

            // Compare if the date has changed, if it has then
            // the date is not valid
            if (objDate.getFullYear() === year&&
                objDate.getMonth() === month &&
                objDate.getDate() === day)
            {                
                if(objDate <= new Date())
                {
                    isValid = true;
                }                   
            }
            return isValid;
        }
    }
};

$(function() {
    var validateButton = $('#btValidate');

    validateButton.click(function(e) {
        var month = parseInt(document.getElementById('month').value, 0),
            day = parseInt(document.getElementById('day').value, 0),
            year = parseInt(document.getElementById('year').value, 0),
            alertBox = $('#alert'),
            isValid = false;

        isValid = validateObject.init(year, month, day);
        var color, message;

        if (isValid === true)
        {
            color = "#008000";
            message = "Your date is valid!";
        }
        else if (isValid === false)
        {
            color = "#F00";
            message = "Your date is not valid!";
        }
        alertBox.css('background', "" + color)
            .html("<p>"+ message +"</p>")
            .stop()
            .animate({
                width: "200px",
                paddingLeft: "75px"
            }, 1750, "easeOutBounce", function() {
                $(this).animate({
                    width: "0px",
                    paddingLeft: "0px"
                }, 1000, "easeInBounce");
        });
    });
});

Working code here: http://jsfiddle.net/vmHjN/140/

这里的工作代码:http: //jsfiddle.net/vmHjN/140/