Form Validation Using AngularJS

A common use case for client side form validation is this:

  1. After the form is submitted, show all invalid input fields using a special color.
  2. If the form is invalid then do not take any action.

AngularJS documentation on form does a good job explaining how to highlight an invalid input field after it gains and loses keyboard focus. But it doesn’t show how to do that for all invalid input fields (irrespective of if it gained input focus) and only after the form is submitted.

Also, in many cases, you will be asked to highlight a div that surrounds an input field and not the input field itself. AngularJS applies styles like ng-invalid to the input field itself and hence will not meet that requirement.

Showing Error Highlight

First, we will write a controller method that will determine if error highlight should be shown for an input field. It will go something like this:

$scope.showError = function(inputName) {
  var form = $scope.myForm;

  return (form.$submitted || form[inputName].$touched) && 
    !form[inputName].$valid;
}

Basically it returns true if the field is invalid and only if the field lost focus or the form was submitted.

Create a style to highlight invalid input.

input.error {
      background: red;
}

In the HTML template use the class if error highlight should be shown.

<form name="myForm" novalidate>
  <input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
</form>

You can also show an error message if you like:

<input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
<br />
<div ng-show="showError('uName')">Tell us your name.</div>

Is the Form Valid?

To see if the form is completely valid use the $valid property of the form. It will be set to false if at least one input field in the form is invalid. An example form submit handler will look like this:

$scope.update = function() {
      console.log("Form submitted");
      if ($scope.myForm.$valid) {
        console.log("The form is valid.");
      } else {
        console.log("Form is invalid");
      }
};

See a working example in Plunker.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s