I have an Angular validation scenario where a field needs to be valid unless it is disabled, in which case it should be ignored.
(I am using ng-messages
for demo purposes, it doesn't affect the $errors
state of the form / field).
How do we clear max
and required
errors when the field is disabled?
<form name="myForm">
<label><input type="checkbox" ng-model="disable"> disable field</label><br>
<input name="width" type="number" ng-disabled="disable" ng-disabled="disable" ng-model="someValue" max="100" required>
<div class="errors" ng-messages="myForm.width.$error">
<div ng-message="required">Please enter a width</div>
<div ng-message="max">Width is over the max permitted</div>
</div>
</form>
myForm.$valid = {{ myForm.$valid }}
Here is a working example on JS Bin: http://jsbin.com/supapotoci/1/edit?html,output
Angular uses directives to match these attributes with validator functions in the framework. Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors that results in an INVALID status, or null, which results in a VALID status.
Solution provided by @pankajparkar is very good.
In case if you don't want any changes in your markup, you can try this.
directive('ngDisabled', function () {
return {
link: function (scope, element, attrs) {
var ngModelController = element.controller('ngModel');
if (!ngModelController) {
return;
}
scope.$watch(attrs.ngDisabled, function (nv, ov) {
if (nv) { //disabled
//reset
Object.keys(ngModelController.$validators)
.forEach(function (type) {
ngModelController.$setValidity(type, true);
})
} else {
ngModelController.$validate();
}
})
}
}
});
Here your input element would be like below using ng-max
& ng-required
Markup
<input name="width" type="number" ng-disabled="disable"
ng-model="someValue" ng-max="disable ? false: 100" ng-required="!disable">
JSBIN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With