Regular Expression date time using MVC Data Annotations

I'm mixing MVC Data Annotations and AngularJs validations ng-pattern. What I've done so far is this thing:

[RegularExpression("/^[0-9]{4}-[0-9]{2}-[0-9]{2} 20|21|22|23|([0-1][0-9]):[0-5][0-9]:[0-5][0-9]$/", ErrorMessage = "Date format: yyyy-mm-dd hh:mm:ss")]

As you can see, I try to format date: yyyy-mm-dd hh:mm:ss. I want to make it 24 hours time. My problem is that form is getting valid when I type:

  • 2015-21 , 2015-22 // 2015-20 is not valid, cannot understand why
  • 2015-12-20 21 // I want user to enter minutes and seconds, because it also has datetimepicker, which is more useful and it sets format as I want

So, why my regular expression is not working as I expect?

--------------Solutions-------------

Your regex does not work as expected because you did not use a ^ anchor (although I guess this expression is anchored, but still it is better to play it safe) and you did not enclose the alternatives into a group, and thus 21, 22, 23 are valid values.

Here is a fixed expression:

^[0-9]{4}-[0-9]{2}-[0-9]{2} (?:20|21|22|23|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$
^^^ ^^

See demo

change your regex instead to be like this

^[0-9]{4}-[0-9]{2}-[0-9]{2} ((20|21|22|23)|([0-1][0-9])):[0-5][0-9]:[0-5][0-9]$

check this Demo

I only changed 20|21|22|23|([0-1][0-9]) in your regex to ((20|21|22|23)|([0-1][0-9]))

Category:regex Time:2018-10-04 Views:0

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.536 (s). 13 q(s)