我正在尝试使用ng-pattern指令验证angularJs中的Email id字段。
但是对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-pattern。
这是原始文档中的示例:
<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
实时示例:http : //plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
如果您对内置的电子邮件验证程序不满意,并且想使用自定义的RegExp模式验证,则可以应用ng- pattern指令,并且根据文档,错误消息可以显示如下:
如果ngModel。$ viewValue与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