3

I am trying to use below date (mm/dd/yyyy) validation pattern using ng-pattern in view.

 ng-pattern="/^(\d{4})-(\d{2})-(\d{2})$/"

As soon as I start typing the date the validation error appears and stays even after having valid date such as 10/15/1988

I tried passing it through controller using var (as shown below) but behaves the same:

In Controller:

  $scope.myPattern = "/^(\d{4})-(\d{2})-(\d{2})$/";

In View:

  ng-pattern="{{myPattern}}"

Note: This both approach not working only in IE9

seUser
  • 1,093
  • 2
  • 10
  • 21

4 Answers4

5

How about:

 /^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/

This will work with both dd/mm/yyyy and yyyy-mm-dd

/^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/.test('04/04/1974')
true
/^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/.test('1974-04-04')
true
Martin
  • 15,820
  • 4
  • 47
  • 56
  • 1
    Thanks Martin. I noticed that with above pattern we can put any numbers for month and date which I want to limit between (1-12) & (1-31) so I am using regex as `/^((0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)[0-9]{2})*$/` for mm/dd/yyyy so how can i use this to allow both mm/dd/yyyy and yyyy-mm-dd – seUser Apr 09 '14 at 15:59
  • This helps me a lot to build my own expression. I also needed validate time, so my pattern results like `/^((0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)[0-9]{2})\s(0[1-9]|1[0-9]|2[0-3])(:([0-5][0-9])){2}$/`. So thanks both for help. – Aramillo Jan 15 '15 at 14:42
  • Aramillo can you please mention above expression for which format ? – VjyV Jan 20 '17 at 13:38
4

Your Regex pattern should be ng-pattern="/^(\d{2})\/(\d{2})\/(\d{4})$/". This would match dates that look like mm/dd/yyyy

Hacknightly
  • 5,109
  • 1
  • 26
  • 27
  • Some how on chrome it works only if use it as ng-pattern="/^(\d{4})-(\d{2})-(\d{2})$/" for mm/dd/yyyy but doesn't work in IE. I already tried what you suggested here but that doesn't work in IE and other browsers. – seUser Apr 08 '14 at 19:21
0

The solution i found for my problem was similar. The regex bellow accepts any date in the format dd/mm/yyyy, whit the year ranging from 1990 to 2020.

<input name="birthDate"
            ng-pattern='/^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[012])\/(19\d\d|20[12]\d)$/' ng-model="newUser.birthDate" type="text">
0

It's because you didn't bind your ng-pattern to a variable in the controller in the proper Angular way ;)

Instead of: $scope.myPattern = "/^(\d{4})-(\d{2})-(\d{2})$/";

It should be: $scope.myPattern = new RegExp(/^(\d{4})-(\d{2})-(\d{2})$/);