Felix Faal Felix Faal - 4 months ago 12
PHP Question

How to display javascript error in form?

Here is how I think the code should look like for the error:

Answer

You've got a couple of options to validate a date in javascript:

1.) new Date("date string") will return 'Invalid Date' if it's invalid. You can check for this and display the error how you wish

function isDateValid(date) {
    var theDate = new Date(date);
    return theDate;
}

Not the best option. new Date(1) for example will return a valid date. 'Invalid Date' will only be thrown if something like new Date('test') is entered

2.) Use a datepicker offered by bootstrap or jquery or some other library. Normally these date pickers will already have date validation in it so you don't have to worry about it. This also gives the user a better interface to picking dates.

this is the best option in my opinion. Most of the date pickers will also have configurable options so you can make the validation more flexable and some even have build in error messages so that part will also be taken care of for you

3.) Use a regex to run against the entered date. You can find many different regular expressions out there that validate all kinds of different formats. One site to look into is regexlib.com

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

This is a good option.

Javascript - Regex to validate date format

Javascript date regex DD/MM/YYYY

Regex for Date Validation in javascript