Angular form validation with field disabled

I have an Angular validation script where the field must be valid if it is not disabled, in which case it should be ignored.

(I use ng-messages for demo purposes, this does not affect the state of $errors form / field).

How do we clear max and required errors when a 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 an example of working with JS Bin: http://jsbin.com/supapotoci/1/edit?html,output

+5
source share
3 answers

Here, your input element will look like this: ng-max and ng-required

Markup

 <input name="width" type="number" ng-disabled="disable" ng-disabled="disable" ng-model="someValue" ng-max="disable ? false: 100" ng-required="!disable"> 

Jsbin

+3
source

The solution provided by @pankajparkar is very good.

If you don't want any changes to 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(); } }) } } }); 
+9
source

ng-required did not work for me with variables mainly because when you use

ng-required="{{test}}" {{test}} returned as a string when ngRequired expects a boolean, fortunately you can use it the same way ngClass works, if you replace your input with the following code, it will work

 <input name="width" type="number" ng-disabled="disable" ng-model="someValue" ng-max="{false: false, true: 100}[!disable]" ng-required="{true : true, false : false}[!disable]" /> 
+2
source

Source: https://habr.com/ru/post/1215675/


All Articles