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!

Asbah Qadeer
  • 61
  • 1
  • 2
  • 9

2 Answers2

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');
    }
Afnan Makhdoom
  • 654
  • 1
  • 8
  • 20
  • 2
    According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse, "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)." – CAK2 Feb 20 '19 at 21:47
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>
Regolith
  • 2,944
  • 9
  • 33
  • 50
  • `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. – Suprabhat Biswal Jul 21 '17 at 07:30
  • 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 – Zander Jan 04 '21 at 16:36
  • forEach function is returning aaaa-mm-dd, testing it with jsFiddle – Zander Jan 04 '21 at 17:28