3

I want to validate if the date input to a function is a valid date. I have the following HTML markup

<div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i> Check in</span>
                        <input id="checkinner" type="date" onchange="datechange(this)" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" placeholder="Enter checkin date of birth">
                    </div>

And the following is my function in javascript

function datechange(element) {


        if (element.value.IsValidDate())
        {
            //code 
        }

    }

Appreciate the love and help!

2

2 Answers 2

1

Try this:

    function datechange(element) {
        var date = Date.parse(element.value.toString());
        if (isNaN(date))
            alert('This is not a date object');
        else
            alert('This is a date object');
    }
Sign up to request clarification or add additional context in comments.

1 Comment

According to developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated)."
0

Try this,

function datechange(element) {
    function isValidDate(s) {
        var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
        return regex.test(s);
    }
[document.getElementById("checkinner").value].forEach(function(s) {
    if(isValidDate(s)){
        console.log(s + ' : ' + isValidDate(s))
    } else {
        console.log('not valid')
    }
});
}
<div class="input-group">
    <span class="input-group-addon">
        <i class="fa fa-calendar"></i> Check in
    </span>
    <input id="checkinner" type="date" onchange="datechange(this)" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" placeholder="Enter checkin date of birth">
</div>

3 Comments

dd/mm/yyyy or dd-mm-yyyy both are valid date format. Splitting a date string with / is not a complete answer to this question.
I don't know why, but if I run this code snippet here, its saying not valid even with a valid date, same happens on my site, but if I run it in jsFiddle, it says it's valid
forEach function is returning aaaa-mm-dd, testing it with jsFiddle

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.