我试图验证一个电子邮件id字段在angularJs使用ng-pattern指令。
但是AngularJs是新的。我需要在用户输入错误的电子邮件ID时显示错误消息。
我下面的代码是我试图解决。帮助我使用ng-pattern获得正确的结果。
<script type="text/javascript" src="/Login/script/ang.js"></script> <script type="text/javascript"> function Ctrl($scope) { $scope.text = 'enter email'; $scope.word = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/; } </script> </head> <body> <form name="myform" ng-controller="Ctrl"> <input type="text" ng-pattern="word" name="email"> <span class="error" ng-show="myform.email.$error.pattern"> invalid email! </span> <input type="submit" value="submit"> </form> </body>
如果要验证电子邮件,请使用type =“email”而不是type =“text”的输入。 AngularJS有开箱即用的电子邮件验证,所以不需要使用ng模式。
下面是原始文档的示例:
<script> function Ctrl($scope) { $scope.text = 'me@example.com'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <br/> <span class="error" ng-show="myForm.input.$error.required"> required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <br> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form>
有关更多详细信息,请阅读此文档:https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
Live示例:http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
如果您对内置的电子邮件验证器不满意,并且要使用自定义的RegExp模式验证,则可以应用ng-pattern伪指令,根据documentation,错误消息可以显示如下:
The validator sets the pattern error key if the ngModel.$viewValue
does not match a RegExp
<script> function Ctrl($scope) { $scope.text = 'me@example.com'; $scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required> <br/><br/> <span class="error" ng-show="myForm.input.$error.required"> required! </span><br/> <span class="error" ng-show="myForm.input.$error.pattern"> Not valid email! </span> <br><br> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/> </form>
Plunker:https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview