Validate form with all fields in AngularJs

What is the best way to validate all the fields in AngularJS.

I have a form with 7 fields, and all are mandatory, and I want to show an error message or change in a border if any of the fields is not valid.

I use below approach. Please tell me is it correct way. What if tomorrow I have 100 fields.

if(!($scope.signInForm.email.$valid)){
    $scope.emailError = true;
}
else {
    $scope.emailError = false;
}
if(!($scope.signInForm.password.$valid)){
    $scope.passwordError = true;
}
else {
    $scope.passwordError = false;
}

Answer

You can handle this in the template, see more information in the doc: https://docs.angularjs.org/guide/forms

From the docs

<form name="myForm" class="css-form" novalidate>
  <div>
    <input type="email" name="input" ng-model="email.text" required>

    <span class="error" ng-show="myForm.input.$error.required">
        Required!
    </span>
    <span class="error" ng-show="myForm.input.$error.email">
        Not valid email!
    </span>
  </div>
  ...

  <!-- If you want to disable the button until all fields are filled in correctly.-->
  <button class="btn btn-default" ng-disabled="myForm.$invalid">Login</button>
</form>

As Alex said it’s also a good idea to look into ngMessages, you can find helpful information here: http://blog.thoughtram.io/2015/06/06/ng-messages-revisited.html

Leave a Reply

Your email address will not be published. Required fields are marked *