fastread homefastrread library fastread menu

AngularJS : Form Validation

Tutorial by:Sumit Chauhan      Date: 2016-08-12 00:24:37

❰ Previous Next ❱

AngularJS has a set of form validation directives you can use. AngularJS validates form fields before copying their value into the $scope properties to which the form fields are bound. If a form field is invalid, its value is not copied into the $scope property it is bound to. Instead the corresponding $scope property is cleared. That is done to prevent the $scope properties from containing invalid values.

Each of the form validating directives are covered in the following sections.

ng-minlength + ng-maxlength

The ng-minlength and ng-maxlength form validation directives can be used to validate the length of data entered in a form field. Here is an example:

<div ng-controller="MyController" >
    <form>
        <input type="text" id="name" ng-model="myForm.name" ng-minlength="5" ng-maxlength="12"> Name <br/>
    </form>

    <div>
        {{myForm.name}}
    </div>
</div>

<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myForm = {};
                $scope.myForm.name = "Jakob aitechtonic";
            } );
</script>

This example sets the ng-minglength to 5 and ng-maxlength to 12. That means that if the text in the input field is less than 5 or more than 12 characters long, the value from the input field will not be copied into the $scope.myForm.name property. You can try this example yourself and see what happens.

Notice the div element which displays the value of the $scope.myForm.name. This wil show you what value was copied from the text field into the $scope.myForm.name property. Notice how it is empty when the text field contains less than 5 or more than 12 characters.

ng-pattern

The ng-pattern directive can be used to validate the value of an input field against a regular expression. Here is an example:

<input type="text" id="name" ng-model="myForm.name" ng-pattern="/^\d+$/"> Name <br/>

The regular expressions must follow the JavaScript regular expression syntax. This example defines a regular expression that matches strings of digits containing at least 1 digit.

ng-required

The ng-required directive checks if the value of the form field is empty or not. Actually, you just use the required attribute of HTML5, and AngularJS detects it automatically.

Checking Field Validation State

If you give the <form> element a name attribute, then the form will be add to the $scope object as a property. Here is an example:

  <form name="myFormNg" ng-submit="myForm.submitTheForm()" >
  ...
  </form>    

When you call a function on the $scope object (a function added to the $scope object by your controller function), you can access the ngFormController object via its name, like this:

$scope.myFormNg

If you add a name attribute to the form fields inside the form, their ngModelController objects will be accessible as properties on the ngFormController object. Here is an example:

  <form name="myFormNg" ng-submit="myForm.submitTheForm()" >
    <input name="firstName" type="text" ng-model="myForm.firstName">
  </form>    

You can now access the ngModelController of the firstName input field like this:

$scope.myFormNg.firstName

Both ngFormController and ngModelController objects contain a set of properties that tell if the form or input field is valid. The properties are:

Property Description
$pristine    True if the form has not been changed (no form fields has changed), false if some fields have been changed.
$dirty The reverse of $pristine - false if the form has not been changed - true if it has.
$valid True if the form field (or the whole form = all form fields) is valid. False if not.
$invalid The reverse of the $valid - false if the field (or all fields in the form) is valid, true if the field (or a single field in the for) is invalid.

You can use these properties to set a matching CSS class on the input fields. Here is an example :

<style>
    .fieldValid {
        border: 1px solid #00ff00;
    }
    .fieldInvalid {
        border: 1px solid #ff0000;
    }
</style>

<div ng-controller="MyController" >
    <form name="myFormNg" >
        <input type="text" ng-class="myForm.getFormFieldCssClass(myFormNg.name)"
               id="name" name="name" ng-model="myForm.name" ng-minlength="2"> Name <br/>
    </form>
</div>

<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope, $http) {
                $scope.myForm = {};

                $scope.myForm.getFormFieldCssClass = function(ngModelController) {
                    //console.log("getting css class: " + ngModelController.$valid) ;
                    if(ngModelController.$pristine) return "";
                    return ngModelController.$valid ? "fieldValid" : "fieldInvalid";
                }
            } );
</script>
    

Notice the ng-class directive on the input field. This directive calls the myForm.getFormFieldCssClass() function using myFormNg.name as parameter. This is the ngModelController for the name input element. The myForm.getFormFieldCssClass() just returns the matching CSS class as a string.

You can also use the validation properties to show or hide div elements with validation messages. Here is the form from before, with a div added:

<div ng-controller="MyController" >
    <form name="myFormNg" ng-submit="myForm.submitTheForm()" novalidate>
    
        <input type="text" ng-class="myForm.getFormFieldCssClass(myFormNg.name)"
               id="name" name="name" ng-model="myForm.name" ng-minlength="2"> Name <br/>

        <div ng-show="myFormNg.name.$invalid">
            You must enter a valid name.
        </div>
    
    </form>
</div>

Notice the ng-show directive on the div element. This directive uses the value of the myFormNg.name.$invalid validation property to determine if the div should be shown or not.

Remember that you can access the $pristine, $dirty, $valid and $invalid properties of the ngFormController too. These properties contain the validation state of the whole form. This button code example disables the submit button if the form is invalid:

<button ng-disabled="myFormNg.$invalid">Submit Form</button>

❰ Previous Next ❱