AngularJS form validation

AngularJS form validation and showing form errors on submit

Posted on January 24, 2015

Here’s how I handle form validation in my AngularJS apps.
I’ve also listed the available directives and properties that we can use for checking our form’s validity.

The advantages of doing it this way are:

  • Form errors are only show when the form has been submitted and not whilst typing.
  • No data is pushed to an api until the form is valid and therefore the data is valid.

Below we have a simple, one field form which will be used to save an email address. I’ve added the novalidate atribute to the form which will prevent any browser validation.

On submit I’ll be running a function called saveEmailAddress() in the controller. This is set using ng-submit=”saveEmailAddress()” on the form tag.

<form name="emailForm" ng-submit="saveEmailAddress()" novalidate>
    <fieldset>

        <label for="email">Email Address</label>
        <input type="email" id="email" name="email" ng-model="newUser.email" required />
        
        <p ng-show="submitted && emailForm.email.$invalid" class="error" >
            Please enter a valid email address
        </p>

        <input type="submit" value="Save Email Address" />

    </fieldset>
</form>

Now lets have a look at the validation.

We’ll be showing a <p> tag with some prewritten error text using the ng-show directive. The code we’re using is:

ng-show=”submitted && emailForm.email.$invalid”

This will show the error when both submitted and emailForm.email.$invalid return true. Lets break these down.

emailForm.email.$invalid

The format for this is formName.inputName.$invalid

As I’ve added the required directive to the input, Angular will only return this input as valid as long as it contains a string.

In Angular the type attribute is also a directive, so by setting the type as email means that Angular will use a regex to validate anything typed in as an email address.

If the input does not pass both of these tests then $invalid will return as true. This won’t show the error yet though as we still need to return the submitted variable as true.

submitted variable

Now it’s a just case of setting the submitted variable to true in the saveEmailAddress() function once the form has been submitted. You can see this in the code below. Don’t forget to apply it to the scope using $scope.submitted so it’s accessible from the form template.

You’ll see that I’ve also added the following conditional to the $scope.saveEmailAddress() function.

if( newUserForm.$valid ){}

Any code within this conditional will only run if the form is completely valid, so this is where you’ll need to put any code that contacts your api.

angular.module('myApp')
  .controller('MyFormController', function ($scope) {

        $scope.saveEmailAddress = function(newUserForm){

            // Set the submitted variable to true so that we can show form errors if required.
            $scope.submitted = true;

            // If form us valid save user
            if( newUserForm.$valid ){
                // Save your form data here
            }

        };

  });

Angular directives for form validation

Here are all the available Angular directives for form validation.

Required

This field is required

<input type="text" required ng-model="" />

Minimum length

The input must be at least this number of characters.

<input type="text" ng-minlength="5" ng-model="" />

Maximum length

The input must be a maximum of this number of characters.

<input type="text" ng-maxlength="20" ng-model="" />

Matches a pattern

The input must match a pattern.

<input type="text" ng-pattern="[a-zA-Z]" ng-model="" />

Email

The input must contain an email address.

<input type="email" name="email" ng-model="" />

Number

The input must contain a number.

<input type="number" name="age" ng-model="" />

Url

The input must contain a Url:

<input type="url" name="url" ng-model="" />

Field object properties

Angular also gives us a number of properties for checking our fields.
These are in the format of formName.fieldName.property:

Field has not been modified
formName.inputFieldName.$pristine

Field has been modified
formName.inputFieldName.$dirty

Field is valid
formName.inputFieldName.$valid

Field is invalid
formName.inputFieldName.$invalid

Form object properties

As well as the field properties, we’re also given some useful properties on the form object itself.
These are in the format of formName.property:

Form has been modified
formName.$dirty

Form has not been modified
formName.$pristine

Form is invalid
formName.$invalid

These can also be modified manually using:

  • formName.$setDirty
  • formName.$setPristine
  • formName.$setValidity