Date validation in javascript [closed]
How to validate ddmmmyyyy and dd-mmm-yyyy date formats using single regex. Please provide solution if anyone have idea
There are two steps to producing a regex like that:
- Learn regular expressions.
- Use your knowledge to write the regex, and ask Stack Overflow if you have problems.
If you want to learn regular expressions then check out Regular-Expressions.info - it's the best site out there. It even has a section on JavaScript-specific regular expressions.
If you don't want to learn, then go away and stop wasting people's time.
var dateFormat = /^(\d{4})-?(\d{2})-?(\d{2})$/
Then you can use it like so:
var match = myString.match(dateFormat);
if (match) {
var year = +match[1], month, day;
var field2 = +match[2], field3 = +match[3];
var monthFirst = true;
if (field2 > 12 && field3 <= 12) {
monthFirst = false;
} else if (field2 <= 12 && field3 <= 12) {
var systemDateFormat = "" + new Date(1970, 5, 13);
monthFirst = systemDateFormat.indexOf("13") > systemDateFormat.indexOf("5");
}
if (monthFirst) {
month = field2;
day = field3;
} else {
month = field3;
day = field2;
}
doSomethingWith(year, month, day);
}
Did you do any research? Assuming “mmm” are letters:
/^[0-9]{2}-?[a-zA-Z]{3}-?[0-9]{4}$/
精彩评论