Thursday, April 10, 2014

Validate british date with ng-pattern.

I was trying to use ng-pattern to validate british date format (dd/mm/yyyy), but I met some problems.
I thought JavaScript regex would work but it didn't.
Something like (0[1-9]) should match 01 to 09. But in ng-pattern, AngularJS ignores the leading zero. I was thinking if it only meets HTML5 pattern. So I went to http://html5pattern.com/ to grab a date pattern which is not ready to validating british date format.
I copied the following pattern from http://html5pattern.com/Dates :

(?:(?:0[1-9]|1[0-2])[\/\\-. ]?(?:0[1-9]|[12][0-9])|(?:(?:0[13-9]|1[0-2])[\/\\-. ]?30)|(?:(?:0[13578]|1[02])[\/\\-. ]?31))[\/\\-. ]?(?:19|20)[0-9]{2}

To validate british format, I chagned it to:

(?:(?:0[1-9]|[12][0-9])[\/\\-. ]?(?:0[1-9]|1[0-2])|(?:30[\/\\-. ]?(?:0[13-9]|1[0-2]))|(?:31[\/\\-. ]?(?:0[13578]|1[02])))[\/\\-. ]?(?:19|20)[0-9]{2}

So to use it in a Input element with AngularJS, it should be like:

<Input ng-pattern="/(?:(?:0[1-9]|[12][0-9])[\/\\-. ]?(?:0[1-9]|1[0-2])|(?:30[\/\\-. ]?(?:0[13-9]|1[0-2]))|(?:31[\/\\-. ]?(?:0[13578]|1[02])))[\/\\-. ]?(?:19|20)[0-9]{2}/">

I hope this can help someone needs it.