簡體   English   中英

如何通過jQuery Validator使用日期月份年份的三個文本框來驗證出生日期

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

我需要通過將jquery驗證器與三個單獨的文本框分別用於日期月份和年份來驗證出生日期。

怎么做請幫忙。

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

我正在使用數據組對文本框進行分組

您應該為此創建自定義驗證方法,並使用validate提供的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");
            }
        }
    });
});

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

我編寫了一個Javascript模塊來處理數據是否有效,您可以在JSFiddle鏈接中查看完整的工作示例。

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

這是執行驗證的模塊:

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

對不起,我不會說英語

您可以分別檢查日期<30或31月月<12年...

我認為當您使用三個文本框時很容易:(僅js

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

此處的工作代碼: http : //jsfiddle.net/vmHjN/140/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM