Reputation: 29867
I need a regular expression in javascript that can test for dates with the following formats:
Sorry, but I am really terrible at regular expressions. This is probably a breeze for a pro. Thanks a milion.
Upvotes: 0
Views: 63
Reputation: 324620
Your first pattern is too different from the others to be meaningfully merged. So: \d{4}-\d\d-\d\d
For the others, you are allowing an optional .
as a separator, and either two- or four-digit years. So you have: \d\d(\.?)\d\d?\1\d\d(?:\d\d)?
The \1
in the above is to basically repeat the (\.?)
's result - ie. a dot if there was a dot before, or nothing if not.
Result:
/^(?:\d{4}-\d\d-\d\d|\d\d(\.?)\d\d?\1\d\d(?:\d\d)?)$/
Upvotes: 1
Reputation: 164
Have you looked here? You don't want to use regex for stuff like this, since aforementioned 99.33.8888 isn't a date.
This clever function could solve your problem:
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
Edit: I forgot you need to find something to validate. You could just run a simple regex like this: [0-9-/\.]{6,10}
, which matches all of your examples
Upvotes: 1