Yaje
Yaje

Reputation: 2831

Validation on Regex in time format

i have a search string :

var searchString = "the times are 21:06 , 03-25 , 16:565";

then i use regex to get the valid times only,

like this :

var reg = /\d{2}[:-]\d{2}/gi

but when i do alert(search.match(reg)); the output is :

21:06,03-25,16:56

16:56 should not display because in my searchString it is 16:565 i'm stuck on how to prevent the last value to be caught on my regex.

How to achieve the validation i wanted?

Any help would be appreciated. Thanks!

Upvotes: 2

Views: 50

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

For exact time match(24 hour format),

\b(?:0[1-9]|1[1-9]|2[0123])[:-](?:0[1-9]|[1-5][0-9]|00)\b

DEMO

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382102

You need to add word boundaries (\b) to your regular expression :

var reg = /\b\d{2}[:-]\d{2}\b/gi;

Upvotes: 2

Related Questions