Web Programming TutorialsLearn about Form Validation in AngularJS

Learn about Form Validation in AngularJS

In this Angularjs tutorial, we’re going to go over dynamic forms and form validation in a bit more advanced way than we’ve seen so far. We’re going to use a lot of the directives we’ve seen before in forms, plus a new one, ng-dirty. ng-dirty has a boolean value equal to true whenever an input box is modified in any way. Otherwise, it’s false. In other words, when a user enters text into an input box, ng-dirty is true. We want to change our box’s appearance (lets change the box color) if the user has text entered, but the input is considered invalid:

 input.ng-dirty.ng-invalid {
      border-color: orange;

Now lets define a controller, which will be used for a list of groceries we will later create:

<div id="List" ng-controller="control">

Lets create a table for the grocery list inside the div:

<h3>Grocery List</h3>
            <th>in basket</th>

Now we’re going to populate our tables with grocery items using the ng-repeat directive:

<tr ng-repeat="grocery in groceries">

We’re also going to use a checkbox for each item, to indicate if it’s been put in the basket or not.

We’ll bind the checkbox to our data model with the ng-model directive, like so:

            <input type="checkbox" ng-model="grocery.inbasket" />

Lets allow the user to add new items, using an input box, at the bottom:

<label>New Item :
        <input type="text" ng-model="itemN" />
      <button ng-click="addItem(itemN)">Add Item</button>

Using the ng-model, ng-click directives and the addItem method, whenever the user clicks on the button, it automatically adds the information (new item) into our $scope object.

If there’s an error(no item was entered), we want to display a message. We’ll create a field to populate:


Lets move on to working with our script.

var newapp = angular.module('newapp', []);

Of course, we need to create our controller as the next step:

newapp.controller('control', function($scope) {
  $scope.groceries= [
    {item: "apples", inbasket: false},
    {item: "mango", inbasket: false},
    {item: "hummus", inbasket: false},
    {item: "bananas", inbasket: false}

We put some grocery items inside our controller scope object as default. Next, we want to create the addItem method which triggers every time the user clicks the button.

 $scope.addItem = function(itemN) {

first, we will check if the input is not undefine or that no value was entered. If both conditions are false, we can add the item into our array with the push method. Otherwise, we give our  missingNewItemError variable a value of “Please Enter an Item”.

if(!(itemN === undefined || itemN === "")){
        item: itemN, inbasket: false
      $scope.missingNewItemError = "";
    } else {
      // Show an error if no item was entered
      $scope.missingNewItemError = "Please Enter an Item";

So this is how we can enter values into arrays using forms while doing some error checking.

Now we’re going to move on to a little more complicated forms of form validation, now that we have the basics down. We’re going to create a new controller, and inside it a form, and a new method that would grab user data using the ng-submit directive.

<div ng-controller="userC">
      <!-- Pass the user data to saveUser() -->
      <form name="formU" ng-submit="saveUser(userInfo)">
        <label> Name:</label>

We are asking the user to enter a first name. We’re going to define an input box with an ng-model of userInfo.name and make it a required field with the ng-require directive. We also want to make sure that the minimum length of the data they entered is 2 characters long.

input type="text" name="name" ng-model="userInfo.name"
        ng-required="true" ng-minlength="2" />

Now we can create a span which would display an error message. The ng-show displays the element it resides in only when its value is true.

<span class="error" ng-show="formU.name.$dirty
        && formU.name.$error.required">Must Enter a First Name </span>

So the span element will display only when the input box has been modified and the field is a required field. Then the error message will display.

Lets create the submit box:

<input type="submit" value="Save" ng-disabled="formU.$invalid"/>

the ng-disabled button disables the button until every field in our form is valid, meaning it has been given input.

Finally, we’ll output all of our users using ng-repeat:

        <li ng-repeat = "item in user">
          {{ 'User: ' + item.name }}

Now lets create a new controller for the users, define defaults for the usee variable, and define the saveUser method, which takes userInfo, which contains all the info about the user,  as a parameter:

newapp.controller('userC', function($scope) {
  $scope.user= [{
    name: "Parakeet web works",
    street: "100 broadway",
    delivery: "Email"
  $scope.saveUser = function(userInfo) {
    if($scope.formU.$valid) {
        name: userInfo.name, street: userInfo.street, delivery: userInfo.delivery
      console.log('User Saved');
    } else {
      console.log('Error : Couldn\'t Save User');

We can create as many information categories for the user as we want, such as address, surname, etc.

In conclusion, we have gone over dynamic forms and learned several different kinds of form validation. We have learned how to add values into arrays using forms and error checking. We’re used a lot of the directives we’ve seen before plus a new one, and got acquainted for the first time with the $invalid input field and form state.


Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article


More article

- Advertisement -