简体   繁体   English

在JavaScript中将日期验证为mm / dd / yyyy格式

[英]validate date to mm/dd/yyyy format in javascript

I have an MVC date field that I am trying to validate to mm/dd/yyyy format. 我有一个MVC日期字段,我正在尝试将其验证为mm/dd/yyyy格式。 I don't want the user to enter 1,2, or 3 digits for year. 我不希望用户输入1,2或3位数字作为年份。 And, I want to make sure a valid date is entered. 而且,我想确保输入有效日期。 Here is the code that I am using: 这是我正在使用的代码:

 <script type="text/javascript">
        $(function () {
            $('.datepicker').datepicker();
            ForceDatePickerFormat();
        });

        function ForceDatePickerFormat() {
            $(".datepicker").on("blur", function (e) {

                var date, day, month, newYear, value, year;
                value = e.target.value;
                if (value.search(/(.*)\/(.*)\/(.*)/) !== -1) {
                    date = e.target.value.split("/");
                    month = date[0];
                    day = date[1];
                    year = date[2];
                    if (year === "") {
                        year = "0";
                    }
                    if (year.length < 4) {
                        alert ("Date year must by 4 digits");
                     }
              }
            });
        }

     </script>

I used "blur" because "keyup" caused a weird issue with the year when a user tried to change it. 我使用“ blur”是因为“ keyup”在用户尝试进行更改时引起了一个奇怪的问题。 "Blur" is good except the user has to click to have the calendar go away, tab doesn't work, and clicking the date doesn't work. 除用户必须单击以使日历消失,选项卡不起作用以及单击日期不起作用外,“模糊”是很好的选择。 If the user hits return, it accepts the date without validating. 如果用户点击回车键,它将接受日期而无需验证。 I need to allow the user to manually enter the date, because they often enter dates way in the future. 我需要允许用户手动输入日期,因为他们以后经常会输入日期。 Does anyone have any suggestions for how to tweak this so that clicking the date closes the calendar, tab closes the calendar, and the date is still validated? 是否有人对如何进行调整有任何建议,以便单击日期关闭日历,单击选项卡关闭日历,并且日期仍然有效?

Here's the snippet you need. 这是您需要的摘录。 All you need to pass date to below function which returns true/false if the given date is valid/invalid 您需要将日期传递给以下函数,如果给定日期有效/无效,则该函数返回true / false

function validateDate(dateValue)
{
    var selectedDate = dateValue;
    if(selectedDate == '')
        return false;

    var regExp = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
    var dateArray = selectedDate.match(regExp); // is format OK?

    if (dateArray == null){
        return false;
    }

    month = dateArray[1];
    day= dateArray[3];
    year = dateArray[5];        

    if (month < 1 || month > 12){
        return false;
    }else if (day < 1 || day> 31){ 
        return false;
    }else if ((month==4 || month==6 || month==9 || month==11) && day ==31){
        return false;
    }else if (month == 2){
        var isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day> 29 || (day ==29 && !isLeapYear)){
            return false
        }
    }
    return true;
}

The above function will: 上面的功能将:

  • Checks for proper date format as MM/DD/YYYY. 检查正确的日期格式为MM / DD / YYYY。
  • Checks whether the given date is valid or not. 检查给定日期是否有效。 Ex: April month is having only 30 days. 例如:4月只有30天。 If we specify day as 31 for the month of April then this function will validate it as invalid date. 如果我们将4月指定为31,则此功能会将其确认为无效日期。
  • Checks for 29th day of February. 检查2月29日。 It will validate as a valid date only if the specified year is a leap year. 仅当指定的年份是a年时,它才会验证为有效日期。

For more info please go through the link: http://www.j2eekart.com/2015/01/date-validation-in-javascript.html 有关更多信息,请通过链接: http : //www.j2eekart.com/2015/01/date-validation-in-javascript.html

Change your code as: 将代码更改为:

<script type="text/javascript">
    $(document).ready(function(){
        $('.datepicker').datepicker();

        $(".datepicker").on("blur", function (e){
            var isValidDate = validateDate(e.target.value);
            if(!isValidDate){
                 alert("Please enter a valid date in MM/DD/YYYY format");
            }
        });
    });

    function validateDate(dateValue)
    {
        var selectedDate = dateValue;
        if(selectedDate == '')
           return false;

        var regExp = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
        var dateArray = selectedDate.match(regExp); // is format OK?

        if (dateArray == null){
            return false;
        }

        month = dateArray[1];
        day= dateArray[3];
        year = dateArray[5];        

        if (month < 1 || month > 12){
            return false;
        }else if (day < 1 || day> 31){ 
            return false;
        }else if ((month==4 || month==6 || month==9 || month==11) && day ==31){
            return false;
        }else if (month == 2){
            var isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day> 29 || (day ==29 && !isLeapYear)){
                return false
            }
        }
        return true;
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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