我正在制作一个有角度的注册表格,并制定了检查有效电子邮件的指令。该指令使用Validator' isEmail(str [, options])
为我检查正则表达式。
该指令名为validator
:
<form name="signUpForm">
<div class="form-group" ng-class="{ 'has-error' : signUpForm.email.$invalid && !signUpForm.email.$pristine }">
<input type="email" name="email" validator="isEmail" placeholder="Email" class="form-control" ng-model="user.email" ng-minlength="3" ng-maxlength="8">
<p ng-show="signUpForm.email.$invalid && !signUpForm.email.$pristine" class="help-block">E-mail is required.</p>
<p ng-show="signUpForm.email.$invalid">E-mail is invalid.</p>
</div>
<button ng-click="signUp()" class="btn btn-primary" ng-disabled="signUpForm.$invalid">Sign Up</button>
</form>
Angular:我想以某种方式返回false
,或者如果无效的电子邮件设置$invalid
,并且显示&#34;电子邮件无效&#34;消息(<p ng-show="signUpForm.email.$invalid">E-mail is invalid.</p>
)。我不确定如何从指令中设置$invalid
属性:
angular
.module('v2v')
.directive('validator', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
link: function (scope, elem, attr) {
elem.bind("keydown keypress", function(event) {
elem.$invalid = validator.isEmail(this.value);
});
}
};
}]);
答案 0 :(得分:1)
Angular输入已内置email验证,但如果您需要添加自己的自定义验证,则可以通过将自己的验证函数添加到模型控制器$validators
来轻松完成此操作:
angular
.module('v2v')
.directive('validator', ['$rootScope', function ($rootScope) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, modelController) {
modelController.$validators.email = function () {
return validator.isEmail(this.value);
}
}
};
}]);
也无需滚动您自己的通知元素,您可以角色ng-messages为您做好准备:
<div ng-messages="signUpForm.email.$error">
<div ng-message="required">Email is required</div>
<div ng-message="email">E-mail is invalid.</div>
</div>