$scope.formName.fieldName.$setValidity is not working

10,960

Solution 1

The problem is that you are trying to select a form input that has no name; thus making it unable to find the field you are trying to invalidate. Here is a working example:

JSBIN: http://jsbin.com/yozanado/1/

Input field with name:

<input id="inputLastName" name="lastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />

Javascript:

$scope.form.lastName.$setValidity("sameName", false);

Solution 2

AngularJS form validation relies on the name of the form and the name of the fields to find the validation models on scope.

For example, if your HTML is:

<form name="form">
     <input name="firstName" ng-model="firstName" />
</form>

You will be able to access the validation $error property on scope using the name attributes:

$scope.form.firstName.$error.sameName

To fix the issues you're having, add a name attribute to your input fields.

JSBin Demo

Share:
10,960
Bulu
Author by

Bulu

Updated on August 21, 2022

Comments

  • Bulu
    Bulu almost 2 years

    I would like to set invalid with angular when firstname is equals to lastname and change the color using styles to red.

    http://jsbin.com/japir/2

    function RegoController($scope) {
      $scope.app = {
        firstName: "Saroj"
      };
    
      $scope.$watch("app.lastName", function(newVal, oldVal) {
        if (!!$scope.app.lastName && !!newVal)
          if (angular.lowercase($scope.app.firstName) === angular.lowercase(newVal)) {
            debugger;
            $scope.form.inputLastName.$setValidity("sameName", false);
          }
    
      });
    }
    
    <body ng-app>
      <div class="container" ng-controller="RegoController">
        <div class="col-lg-4">
          <form name="form">
            <div class="form-group">
              <label for="inputFirstName">First Name</label>
              <input id="inputFirstName" class="form-control" type="text" ng-model="app.firstName" placeholder="Enter your firstname" required ng-minlength="3" ng-maxlength="20" />
            </div>
            <div class="form-group">
              <label for="inputLastName">Last Name</label>
              <input id="inputLastName" class="form-control" type="text" ng-model="app.lastName" placeholder="Enter your last name" required ng-minlength="3" ng-maxlength="20" />
            </div>
            <div class="form-group">
              <label for="inputEmail">Email</label>
              <input id="inputEmail" class="form-control" type="email" ng-model="app.email" placeholder="Enter your email" required />
            </div>
            <div class="form-group">
              <input type="submit" class="btn btn-primary" value="Save" />
            </div>
          </form>
          {{app}}
        </div>
      </div>
    </body>