Knowing which validations failed in a form with AngularJS

Knowing which validations failed in a form with AngularJS

Sometimes we want to submit a form and know which validations failed, and in which fields. Perhaps

Sometimes we want to submit a form and know which validations failed, and in which fields. Perhaps we don’t know how to do it, but we do know that we don’t want to assess each field separately. Here we are going to see an alternative.

We start off on a page with a form which has several inputs with different validations.

<form name="form" class="form" novalidate>
  <div class="form-group">
    <label for="nombre">Nombre</label>
    <input type="text" class="form-control" id="nombre" name="nombre" ng-model="name" required/>
  </div>
  <div class="form-group">
    <label for="edad">Edad</label>
    <input type="number" class="form-control" id="edad" name="edad" ng-model="edad" required/>
  </div>
  <div class="form-group">
    <label for="pais">Pais</label>
    <input type="text" class="form-control" id="pais" name="pais" ng-model="pais" required minlength="2" maxlength="3"/>
  </div>
  <input type="submit" class="btn btn-primary btn-block" value="Aceptar"/>
</form>

If we go over the documentation of AngularJS about controllers, we will see that the form has an $invalid property and an $error property, which has a map with the type of validation (required, maximum, minimum, etc.) as key and a collection with the fields where each validation failed as value. That’s perfect! We just have to iterate that with a repeater:

<div class="alert alert-danger" ng-show="form.$invalid">
  <ul>
      <li ng-repeat="(errorType, components) in form.$error">{{errorType}}: {{components}}</li>
  </ul>

However, we get this:

The documentation doesn’t say much more. The problem is that the objects belong to the kind ngModelController and their properties are hidden (they start with $). Therefore, in order to do something more generic to show our validation errors, we can take the following action:

<div class="alert alert-danger" ng-show="form.$invalid">
  <div ng-repeat="(errorType, components) in form.$error">
    <h4>{{errorType}}</h4>
    <ul>
      <li ng-repeat="(key,value) in components">El campo {{value.$name}} tiene un valor invalido: {{value.$viewValue || '[vacio]'}}</li>
    </ul>
  </div>

And we get this:

Are you looking for the best technical solution for your company? Contact us for more information and we will get back to you!