2

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?

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

actually yes, this works fine with AngularJs validations (javascript), but MVC seems to have different syntax or so. My ModelState.IsValid returns false on this date. I also use another regex for numbers, so that is fine. Maybe you know, what occurs this problem?
I do not know what the other regex look like but my suggested regex should work with any regex engine unless it does not support noncapturing groups. Which is not the cae I believe. What date do you mean?
1

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]))

1 Comment

thanks for your answer too, I was affraid to add parentesis, however I have now another problem, which I posted upper in comments, hope to find out the solution by myself ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.