javascript 日期的 Angular ng-pattern 不适用于 IE9
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22946113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular ng-pattern for date not working on IE9
提问by seUser
I am trying to use below date (mm/dd/yyyy) validation pattern using ng-pattern in view.
我正在尝试在视图中使用 ng-pattern 使用以下日期(mm/dd/yyyy)验证模式。
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
一旦我开始输入日期,验证错误就会出现并且即使在有效日期(例如 10/15/1988)之后仍然存在
I tried passing it through controller using var (as shown below) but behaves the same:
我尝试使用 var (如下所示)通过控制器传递它,但行为相同:
In Controller:
在控制器中:
$scope.myPattern = "/^(\d{4})-(\d{2})-(\d{2})$/";
In View:
在视图中:
ng-pattern="{{myPattern}}"
Note: This both approach not working only in IE9
注意:这两种方法都不适用于 IE9
回答by Martin
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
这将适用于 dd/mm/yyyy 和 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
回答by Hacknightly
Your Regex pattern should be ng-pattern="/^(\d{2})\/(\d{2})\/(\d{4})$/"
. This would match dates that look like mm/dd/yyyy
您的正则表达式模式应该是ng-pattern="/^(\d{2})\/(\d{2})\/(\d{4})$/"
. 这将匹配看起来像的日期mm/dd/yyyy
回答by Daniel Vilas-Boas
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.
我为我的问题找到的解决方案是相似的。下面的正则表达式接受格式为 dd/mm/yyyy 的任何日期,包括 1990 年到 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">
回答by Samantha Guergenenov
It's because you didn't bind your ng-pattern to a variable in the controller in the proper Angular way ;)
这是因为您没有以正确的 Angular 方式将 ng-pattern 绑定到控制器中的变量;)
Instead of: $scope.myPattern = "/^(\d{4})-(\d{2})-(\d{2})$/";
而不是: $scope.myPattern = "/^(\d{4})-(\d{2})-(\d{2})$/";
It should be: $scope.myPattern = new RegExp(/^(\d{4})-(\d{2})-(\d{2})$/);
应该是:$scope.myPattern = new RegExp(/^(\d{4})-(\d{2})-(\d{2})$/);