[英]Angular form validation - hide errors on field update
我有一个表单,其中当前包含一个字段,其中包含很少的验证规则:
<form name="my_form" novalidate ng-controller="FormController">
<label>Your Name:</label>
<input type="text"
name="name"
placeholder="Your Name"
ng-model="form.name"
ng-minlength="3"
ng-maxlength="20"
unique
required />
<button ng-click="submitForm()">Submit</button>
<div class="error"
ng-show="my_form.isSubmitted"
ng-messages="my_form.name.$error">
<div ng-messages-include="errors.html"></div>
</div>
</form>
我的领域针对以下方面进行了验证:
我正在使用ng- messages在输入字段附近显示错误消息。 这是我的errors.html模板:
<div ng-message="required">This field is required.</div>
<div ng-message="minlength">This field is too short.</div>
<div ng-message="maxlength">This field is too long.</div>
<div ng-message="unique">The value of this field must be unique.</div>
仅在按下“ Submit”按钮后才应开始验证( submitForm()函数将my_form.isSubmitted标志设置为true并显示我的错误div)
这是我的js代码:
var app = angular.module('formValidation', ['ngMessages']);
app.controller('FormController', function($scope) {
$scope.submitForm = function() {
$scope.my_form.isSubmitted = true;
};
});
app.directive('unique', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, ele, attrs, ctrl) {
var names = ['Dmitry', 'Alexander', 'Elizabeth'];
ctrl.$parsers.push(function(value) {
if (names.indexOf(value) > -1) {
ctrl.$setValidity('unique', false);
return false;
}
ctrl.$setValidity('unique', true);
return true;
});
}
};
);
一切正常,但是我现在想做的是隐藏错误,如果在显示错误后修改了该字段(直到再次按下提交按钮)。
我想到的第一个主意是在error div的ng-show指令中添加另一个条件,以检查相应字段是否已更新,如果已更新,则不应显示错误。 就像是:
<div class="error"
ng-show="!my_form.name.isUpdated && my_form.isSubmitted"
ng-messages="my_form.name.$error">
<div ng-messages-include="errors.html"></div>
</div>
因此,单击按钮时,我可以将所有表单字段的isUpdated标志设置为false,而在输入update时,可以将其设置为true。 但是在我看来,这种解决方案远非优雅。 我敢肯定,有一种更好的方法可以实现这种行为。 有任何想法吗?
我当前的解决方案(可能不是最好的解决方案):
<input type="text"
name="name"
placeholder="Your Name"
ng-model="form.name"
ng-minlength="3"
ng-maxlength="20"
unique
updatable
required />
<button ng-click="submitForm()">Submit</button>
<div class="error"
ng-show="!my_form.name.isDirty && my_form.isSubmitted"
ng-messages="my_form.name.$error">
<div ng-messages-include="errors.html"></div>
</div>
我向字段添加了可更新的新指令,并更新了错误div的显示条件:
ng-show="!my_form.name.isDirty && my_form.isSubmitted"
指令:
app.directive('updatable', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, ele, attrs, ctrl) {
ele.bind('input', function() {
scope.$apply(function() {
ctrl.isDirty = true;
});
);
}
};
});
并小的更新了SubmitForm函数,该函数现在将我的字段的isDirty标志设置为false:
$scope.submitForm = function() {
$scope.my_form.isSubmitted = true;
$scope.my_form.name.isDirty = false;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.