0

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?

Uniruddh
  • 4,427
  • 3
  • 52
  • 86
Night Owl
  • 55
  • 2
  • 13
  • 1
    This may help http://stackoverflow.com/questions/19820257/javascript-date-validation-dd-mm-yyyy-age-checking – karmadip dodiya Oct 27 '15 at 05:07
  • Or use this regular expression in the code ::: -- '((?:[0]?[1-9]|[1][012])[-:\\/.](?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))[-:\\/.](?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])'; – Pradip Oct 27 '15 at 06:52

1 Answers1

1

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>
Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12
  • This is great, thanks for your answer! Now that I put the datepicker in there, the client really likes the popup calendar. Can I use your code within the datepicker (ie: put it after the on."blur" section) instead of the date check that I have? – Night Owl Oct 28 '15 at 06:40
  • It won't let me upvote it. I click the up arrow and it turns to a "1" but then changes back to 0. – Night Owl Oct 29 '15 at 00:03
  • I've tried many different ways to get this to work within my datepicker code, I can't make it happen. Do I just copy your code and replace what I have for function ForceDatePickerFormat()? Just literally use your function instead of mine? Or, put yours under the on."blur"? Sorry, I'm very new to this. – Night Owl Nov 01 '15 at 20:00
  • Thank you! You have no idea how much this helps. I've been working this on both the client and server side...this is perfect! – Night Owl Nov 02 '15 at 06:05
  • @NightOwl where are you from?? – Viswanath Donthi Nov 02 '15 at 06:51
  • Arizona. I still can't make this work. It will not validate the date if entered with datepicker, as if it doesn't recognize that something was entered into the field. If I put the date in manually, it works. – Night Owl Nov 02 '15 at 10:13