Validating User Input on a Form in Angular JS

Dhananjay Kumar / Wednesday, August 26, 2015

 

I have often seen entry-level developers struggling with user input validation in AngularJS single page applications. In this post, I will give a quick but useful introduction of validations in AngularJS; consider this post as a base learning document from which you can do further learning.
Let’s start with an example as shown in the image below. You have a registration form with three fields with the following restrictions.

1.       Name: Required

2.       Email: Required and type Email

3.       Password: Required, type password and minimum length 6

We want to validate the rules mentioned above on the client side. There are two ways client-side validation can be done in an AngularJS based single page application:

1.       Using the HTML5 validations

2.       Using the AngularJS validation directives

3.       A Combination of both

 
HTML5 validation
Here we’ve created the Add user form shown above using the mark up listed below:
  <div class="row">
                <form name="adduser" ng-submit="AddUser(adduser.$valid)">                   
                    <div id="name-group" class="form-group-lg">
                        <input type="text"
                               required
                               name="name"
                               ng-model="userfullName"
                               class="form-control"
                               placeholder="Full Name">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="email"
                               required
                               name="email"
                               ng-model="useremail"
                               class="form-control"                              
                               placeholder="Email">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="password"
                               required
                               ng-model="userpassword"
                               name="password"                             
                               class="form-control "
                               placeholder="Password atleast 6 character">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <button type="submit" class="form-control btn btn-info">
                       </button>
                    </div>
                </form>
            </div>
 
We are applying all the required user validation using the HTML 5 validations.  When we submit a form with invalid user data, HTML5 will return an error as shown below:
 
This error on the UI is returned by HTML5. HTML5 validation will not work in browsers that don’t support HTML5. Some points about validation techniques are as follows:

·         Validation will not work in browsers does not support HTML5

·         HTML 5 error (as shown in the image above) will be displayed for the invalid user input

·         Invalid user input will be set to undefined value in the controller

Now let’s try to read the value of user inputs in the controller. Do not forget to attach a controller to the form.
 
console.log('user name : ' + $scope.userfullName);
        console.log('user email : ' +$scope.useremail);
        console.log('user password :' +$scope.userpassword);
 
Here we are validating the form and user inputs using HTML 5 validation. We are able to submit the form even if some of the inputs are invalid. Invalid input value would be set to the undefined in the controller. As you see in the below image that for the email field, the input is invalid and in the controller, invalid email value is set to undefined.
 
 
 
Two important observations can be drawn from the above validation technique:

1.       We were able to submit the form even if the form was not valid

2.       For the invalid inputs, the value was set to undefined in the controller

If we want the form not to be submitted when it is invalid, then instead of ng-click on the button, we will use ng-submit directive on the form itself:
 
  <div class="row">
                <form name="adduser" ng-submit="AddUser(adduser.$valid)">                   
                    <div id="name-group" class="form-group-lg">
                        <input type="text"
                               required
                               name="name"
                               ng-model="userfullName"
                               class="form-control"
                               placeholder="Full Name">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="email"
                               required
                               name="email"
                               ng-model="useremail"
                               class="form-control"                              
                               placeholder="Email">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="password"
                               required
                               ng-model="userpassword"
                               name="password"                             
                               class="form-control "
                               placeholder="Password atleast 6 character">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <button type="submit" class="form-control btn btn-info">
                       </button>
                    </div>
                </form>
            </div>
 
In the ng-submit we calling a function AddUser from the controller with a parameter formname.$valid. This submit function will be only called when a form is valid or in other words, all the user input of the form is valid. Keep in mind that in this case from would not be submitted if the form is not valid. In the previous example, we saw that even if the form was invalid, we were able to submit the form and for invalid input fields undefined value was getting passed in the controller. However here we cannot submit the form if it is not valid.
 
AngularJS validation
Another option is to validate the user input only using the AngularJS directives. To work with only AngularJS validation, we need to perform the following tasks –

·         Use novalidate on the form to disable HTML validation.

·         Instead of HTML validations use AngularJS validation directives.

We can create the form with required user validations using only the AngularJS validation directives as shown in the listing below:
<form name="adduser" novalidate>
                    <!-- NAME -->
                    <div id="name-group" class="form-group-lg">
                        <input type="text"
                               ng-required="true"
                               name="name"
                               ng-model="userfullName"
                               class="form-control"                              
                               placeholder="Full Name">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="email"
                               ng-required="true"
                               name="email"
                               ng-model="useremail"
                               class="form-control"                             
                               placeholder="Email">
                                            </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="password"
                               ng-required="true"
                               ng-model="userpassword"
                               name="password"
                              ng-minlength="5"
                               class="form-control "
                               placeholder="Password atleast 6 character">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <button type="submit" ng-click="AddUser()" class="form-control btn btn-info">
                          Register
                        </button>
                    </div>
                </form>
 
We are using the novalidate attribute to disable HTML5 validation, and validating the following user input:

1.       All the fields are required.

2.       Minimum length of the password field is 6.

On submitting the form, user input will be validated using the AngularJS validation directives. If the user does not provide a value for the name or provides less than six characters for the password field then the form would be submitted with the value undefined for the invalid user inputs.
 
 
As you might have noticed, when we do not use HTML 5 validations and rely on the AngularJS validations, there are two things that happen:

1.       Forms are submitted even if all the user inputs are not valid

2.       No error message is displayed for the invalid user input

 
Disable Submit button if Form is not valid
We can disable the submit button if the form is not valid or any of the user input is invalid. Let us use AngularJS $valid property to disable the submit button if the form is invalid:
<form name="adduser" novalidate>
                    <!-- NAME -->
                    <div id="name-group" class="form-group-lg">
                        <input type="text"
                               ng-required="true"
                               name="name"
                               ng-model="userfullName"
                               class="form-control"                              
                               placeholder="Full Name">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="email"
                               ng-required="true"
                               name="email"
                               ng-model="useremail"
                               class="form-control"                             
                               placeholder="Email">
                                            </div>
                    <div id="name-group" class="form-group-lg">
                        <input type="password"
                               ng-required="true"
                               ng-model="userpassword"
                               name="password"
                              ng-minlength="5"
                               class="form-control "
                               placeholder="Password atleast 6 character">
                    </div>
                    <div id="name-group" class="form-group-lg">
                        <button type="submit" ng-disabled="!adduser.$valid" ng-click="AddUser()" class="form-control btn btn-info">
                          Register
                        </button>
                    </div>
                </form>
 
Here we’re using the ng-disabled directive to disable the button. As you see in the image below, a $valid property is used to check whether the form is valid or not. Do not forget that adduser is the name of the form.
 
Show the error message
Unlikely HTML5 validation rules, by default AngularJS validation directives, and does not display any error message for the invalid user input. However, we can show the error message as shown in the listing below. We are using $valid and $pristine properties to display the error message:
 
<form name="adduser" novalidate>
                    <!-- NAME -->
                    <div id="name-group" class="form-group-lg">
                        <input type="text"
                               ng-required="true"
                               name="name"
                               ng-model="userfullName"
                               class="form-control"
                               placeholder="Full Name">
                        <span class="help-block"
                               ng-show="adduser.name.$invalid && !adduser.name.$pristine">
                            You name is required.
                        </span>
                  </div>
 
The error message will be displayed as shown in the image below:
 
 
 
Styling the error message and input control
Using the $valid and $pristine properties we can display the error message and create a style for it using the listing below:
<form name="adduser" novalidate>
                    <!-- NAME -->
                    <div id="name-group" class="form-group-lg" ng-class="{ 'has-error' : adduser.name.$invalid && !adduser.name.$pristine }">
                        <input type="text"
                               ng-required="true"
                               name="name"
                               ng-model="userfullName"
                               class="form-control"
                               placeholder="Full Name">
                        <span class="help-block"
                               ng-show="adduser.name.$invalid && !adduser.name.$pristine">
                            You name is required.
                        </span>
                  </div>
 
Now, the error message will be displayed with the style as shown in the image below:
 
 
 
 
Reading Validation properties in the Controller
 
In the controller, we can read whether the form is valid or not, using the $valid property on the form name. If all the user input is valid we will get a value of $valid property true. Whether the form is valid or not can be checked in the controller as shown in the listing below:
 
 
if ($scope.adduser.$valid) {
            alert('all inputs are valid ');
        }
        else
        {
            alert('all inputs are not valid ');
        }
 
 
 
AngularJS validation properties
 
While working with AngularJS validation, the following are important properties:

 



 
 
We can use these properties along with the form name to perform various validations tasks.  
 
So there you have it! We’ve explored how you can use a combination of HTML5 validations and AngularJS validation directives to validate the form and user inputs in AngularJS. I hope you find this post useful – thanks for reading!