Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for MM/DD/YYYY in Javascript

I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:

function isGoodDate(dt){
    var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
    return reGoodDate.test(dt);
}

and this is how I call it in my form validation

if(!isGoodDate(userInput[1].value)){
           alert("date not in correct format of MM/dd/YYYY");
           return false;  
        }

now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?

like image 918
Mark Sandman Avatar asked Jun 19 '11 13:06

Mark Sandman


People also ask

How do you check if the date is in dd mm yyyy format in JavaScript?

The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss. sssZ . If the ISO representation of the Date object starts with the provided string, then the date string is valid and formatted as DD/MM/YYYY .

How would you match the date format dd mm yyyy?

To match a date in mm/dd/yyyy format, rearrange the regular expression to ^(0[1-9]|1[012])[- /.] (0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d$. For dd-mm-yyyy format, use ^(0[1-9]|[12][0-9]|3[01])[- /.]

Does JavaScript have regular expression?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .


2 Answers

Maybe because you are declaring the isGoodDate() function, and then you are calling the isCorrectDate() function?

Try:

function isGoodDate(dt){
    var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
    return reGoodDate.test(dt);
}

Works like a charm, test it here.

Notice, this regex will validate dates from 01/01/1900 through 31/12/2099. If you want to change the year boundaries, change these numbers (19|20) on the last regex block. E.g. If you want the year ranges to be from 01/01/1800 through 31/12/2099, just change it to (18|20).

like image 40
Shef Avatar answered Oct 13 '22 01:10

Shef


Attention, before you copy+paste: The question contains some syntactic errors in its regex. This answer is correcting the syntax. It is not claiming to be the best regex for date/time parsing.

Try this:

function isGoodDate(dt){
    var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
    return reGoodDate.test(dt);
}

You either declare a regular expression with:

new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")

Or:

/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/

Notice the /

like image 162
Jan Avatar answered Oct 13 '22 01:10

Jan