这是角度非常基本的问题,但我无法解决这个问题;我想使用ng-pattern
验证电子邮件地址,但在某些情况下失败了
请参阅working Demo
条件失败:当我写some@thing
时,它验证了OK,但这不正确。请帮我解决这个基本问题。
(function() {
var app = angular.module('app', []);
app.controller ('MainCtrl', function ($scope){
var vm = this;
vm.title = "Email Validation";
vm.email = "";
vm.email_regex = '^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$';
});
})();
<html ng-app="app">
<head>
<link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="bootstrap@3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script data-require="angular.js@*" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
<h2>{{vm.title}}</h2>
<div class="col-md-12">
<form name="emailForm" novalidate="">
<div class="form-group" ng-class="{'has-error': emailForm.username.$touched && emailForm.username.$invalid }">
<label>Email</label>
<input type="email" class="col-md-12 form-control" name="username" ng-model="vm.email" ng-pattern="vm.email_regex" required />
</div>
<div ng-if="emailForm.username.$touched && emailForm.username.$invalid" ng-messages="emailForm.username.$error" class="text-danger">
<span ng-message="pattern">Invalid Username.</span>
<span ng-message="required">Please enter Username.</span>
</div>
</form>
</div>
<div class="row"></div>
<hr />
<pre>{{ emailform.username.$error | json }}</pre>
</body>
</html>
答案 0 :(得分:1)
您需要删除' '
来自vm.email_regex
DEMO:http://plnkr.co/edit/tbLP5syvZEq7qtE4X75o?p=preview
请参阅:Why is Angularjs ng-pattern not working with the following regexp?
(function() {
var app = angular.module('app', []);
app.controller ('MainCtrl', function ($scope){
var vm = this;
vm.title = "Email Validation";
vm.email = "";
vm.email_regex = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
});
})();