我有一个表单验证,但似乎无法显示我的验证错误消息。
<div class="col-sm-8">
<input name="email" class="form-control" type="text" ng-model="formdata.email" email-valid required>
<div class="ng-cloak" ng-show="registration_form.email.$touched">
<p class="field_error" ng-show="registration_form.email.$error.required">Email is required</p>
<p class="field_error" ng-show="registration_form.email.$error.emailValid">Email is invalid</p>
<p class="field_error" ng-show="registration_form.email.$error.minlength">Email is too short</p>
</div>
</div>
我的控制器的一部分:
var email = Validators.validateEmail(data.email);
if (email != true) {
$scope.registration_form.email.$error.emailValid = true;
}
任何帮助将不胜感激。
答案 0 :(得分:0)
您需要使用自定义验证器。
例如,下面的电子邮件只有在长度超过13(@前有5个以上的字符)并且以 .com 或 .net 结尾时才有效。
在功能emailValid
中,您可以检查任何内容。
var app = angular.module('FormExample', []);
var EMAIL_REGEXP = /^[a-z0-9](\.?[a-z0-9]){3,}@mail\.(com|ru)$/;
app.directive('customEmail', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$validators.emailValid = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (EMAIL_REGEXP.test(viewValue)) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="FormExample">
<div>
<form novalidate name="registration_form">
<label>Email:
<input custom-email name="email" type="text" ng-model="email" minlength=14 required>
</label>
<div class="ng-cloak" ng-show="registration_form.$submitted || registration_form.email.$touched">
<p ng-show="registration_form.email.$error.required">Email is required</p>
<p ng-show="registration_form.email.$error.emailValid">Email is invalid</p>
<p ng-show="registration_form.email.$error.minlength">Email is too short</p>
</div>
<br>
<input type="submit" value="Save">
</form>
</div>
</div>