Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 /


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...