如果您想验证电子邮件,请使用 type="email" 而不是 type="text" 的输入。 AngularJS 具有开箱即用的电子邮件验证功能,因此无需为此使用 ng-pattern。
这是原始文档中的示例:
<script>
function Ctrl($scope) {
$scope.text = '[email protected] /cdn-cgi/l/email-protection';
}
</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 https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
实例:http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
如果您对内置电子邮件验证器不满意并且想要使用自定义 RegExp 模式验证,则可以应用 ng-pattern 指令并根据文档 https://docs.angularjs.org/api/ng/directive/ngPattern错误消息可以这样显示:
如果 ngModel.$viewValue ,则验证器设置模式错误键
与正则表达式不匹配
<script>
function Ctrl($scope) {
$scope.text = '[email protected] /cdn-cgi/l/email-protection';
$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>
笨蛋:https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview