Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular form validation with disabled field

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

like image 368
Ade Avatar asked Mar 19 '15 12:03

Ade


People also ask

What is form validation in angular?

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.


2 Answers

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();
                }
            })
        }
    }
});
like image 167
Vinay K Avatar answered Sep 19 '22 05:09

Vinay K


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

like image 30
Pankaj Parkar Avatar answered Sep 21 '22 05:09

Pankaj Parkar