Kumaresan Sd
Kumaresan Sd

Reputation: 1516

How to write regex for date format validation?

I have written regex like below:

/^(\d{4}\-\d\d\-\d\d)|(\d{4}\-\d\d\-\d\d([tT][\d:\.]*){1})([zZ]|([+\-])(\d\d):?(\d\d))?$/.test("1995-01-01")

It is working fine but even if i give wrong format also return true as value please refer below screenshot:

tt

Upvotes: 2

Views: 137

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

The problem with the current regex is that you have two alternations that are each anchored on one side only, the first at the start and the last at the end.

The quick fix would be

^(?:(\d{4}-\d\d-\d\d)|(\d{4}-\d\d-\d\d([tT][\d:.]*))([zZ]|([+-])(\d\d):?(\d\d))?)$
 ^^^                 ^                                                          ^

See this regex demo.

However, since both alternatives start with the same pattern, it makes sense to write it as common_prefix(?:second_alternative_part_after_prefix)?.

You also have lots of groups in the pattern that seem redundant, same as {1} quantifier that is never necessary in a pattern.

Here is a fixed version of your regex:

/^\d{4}-\d\d-\d\d(?:t[\d:.]*(?:z|[+-]\d\d:?\d\d)?)?$/i

Or, precising it further on to match year-month-days:

/^[12]\d{3}-(?:0?[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])(?:t[\d:.]*(?:z|[+-]\d\d:?\d\d)?)?$/i

If the last \d\d:?\d\d are for minutes and seconds you may replace it with [0-5][0-9]:?[0-5][0-9].

See the regex demo and the regex graph:

enter image description here

enter image description here

Upvotes: 2

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4836

Try this:

const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$)/;

console.log(regex.test('1995-01-01')) //true
console.log(regex.test('1995-01-016')) //false

enter image description here

Upvotes: 3

Related Questions