Displaying Form Validation Errors

Problem

You wish to show validation errors to the user by marking the input field red and displaying an error message.

Solution

We can use the ng-show directive to show an error message if a form input is invalid and CSS classes to change the input element’s background color depending on its state.

Let us start with the styling changes:

<style type="text/css">
  input.ng-invalid.ng-dirty {
    background-color: red;
  }
  input.ng-valid.ng-dirty {
    background-color: green;
  }
</style>

And here is a small part of the form with an error message for the input field:

<label>Firstname</label>
<input name="firstname" type="text" ng-model="user.firstname" required/>
<p ng-show="form.firstname.$invalid && form.firstname.$dirty">
  Firstname is required
</p>

You can find the complete example on github.

Discussion

The CSS classes ensure that we initially show the fresh form without any classes. When the user starts typing in some input for the first time, we change it to either green or red. That is a good example of using the ng-dirty and ng-invalid CSS classes.

We use the same logic in the ng-show directive to only show the error message when the user starts typing for the first time.