简体   繁体   中英

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. I don't want the user to enter 1,2, or 3 digits for year. 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" 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

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.
  • Checks whether the given date is valid or not. Ex: April month is having only 30 days. If we specify day as 31 for the month of April then this function will validate it as invalid date.
  • Checks for 29th day of February. It will validate as a valid date only if the specified year is a leap year.

For more info please go through the link: 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>

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