Recent Tutorials and Articles
    Form Validation in AngularJS
    Published on: 2018-05-25 16:05:39
    Posted By: Sumit Sain

    This tutorial demonstrates how to do form validation in AngularJs framework along with explaining the basic directives such as ng-app. ng-controller and ng-show used in it.

    We will be creating following three files in order to demonstrate the form validation in AngularJs -

    1. form-validation.html file containing the form field structure
    2. form-validation.css file for adding basic style to our form to give it a decent look
    3. form-validation.js file containing the AngularJs controller with regular expressions needed for fields validations

    This is how our project structure looks like -

    In the next section, we will talk about three files that you will need to create.

    form-validation.html

    Here is how our HTML file form-validation.html looks like -

    form-validation.html
    <!DOCTYPE html>
    <html ng-app="myApp">
    <head>
    <meta charset="ISO-8859-1">
    <title>Form Validation</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="js/form-validation.js"></script>
    <link rel="stylesheet" type="text/css" href="css/form-validation.css" />
    </head>
    <body>	
    <form name="form" ng-controller="Ctrl" >
    <fieldset>
    <legend id="table_heading">Form Validation Demo</legend>
        <table>
       	<tr>
    	    <div>
    	    <td><label>Username: </label></td>
    	    <td><input type="text" name="username" ng-model="user.username" ng-pattern="username"
    	        ng-minlength="5" ng-maxlength="50" placeholder="Username" required autofocus>
    		<span ng-show="form.username.$dirty && form.username.$error.required">Required!</span>
    		<span ng-show="form.username.$dirty && form.username.$error.minlength">Too short!</span>
    		<span ng-show="form.username.$dirty && form.username.$error.maxlength">Too Long!</span>
    		<span ng-show="form.username.$dirty && form.username.$error.pattern">Single word only!</span>
    	    </td>
    	    </div> 
    	</tr>
    	<tr>
    	    <div>
    	    <td><label>Password:</label></td>
    	    <td><input type="password" name="pwd" ng-model="user.pwd" placeholder="Password"
    	        ng-minlength="5" ng-maxlength="9" required>
    	        <span ng-show="form.pwd.$dirty && form.pwd.$error.required">Required!</span>
    	        <span ng-show="form.pwd.$dirty && form.pwd.$error.minlength">Too short!</span>
    	        <span ng-show="form.pwd.$dirty && form.pwd.$error.maxlength">Too Long!</span>
    	    </td>
    	    </div>
            </tr>
    	<tr>
    	    <div>
    	    <td><label>Email-Id:</label></td>
    	    <td><input type="email" name="email" ng-model="user.email" placeholder="Email" required>
    	        <span ng-show="form.email.$dirty && form.email.$error.required">Required!</span>
    	        <span ng-show="form.email.$dirty && form.email.$error.email">Not an email id!</span>
    	    </td>
    	    </div>
            </tr>
            <tr>	
    	    <div>
    	    <td><label>PhoneNo:</label></td>
    	    <td><input type="text" placeholder="+33-333-33333" ng-model="user.phone" name="phone"
    	        ng-pattern="pho_numbr" required>
                    <span ng-show="form.phone.$dirty && form.phone.$error.required">Required!</span>
                    <span ng-show="form.phone.$dirty && form.phone.$error.minlength">Not less than 10 digit</span>
                    <span ng-show="form.phone.$dirty && form.phone.$error.maxlength">Not More than 11 digit</span>
                    <span ng-show="form.phone.$dirty && form.phone.$error.pattern">
                    Pls Match Pattern[+12-236-23658 or 12-236-23658]</span>
                </td>
                </div>
        	</tr>
        	<tr>
                <td></td>
                <td><button ng-disabled="form.$invalid">Register</button></td>
        	</tr>	
        </table>
    </fieldset>
    </form>
    </body>
    </html>
    
    

    Let's discuss some of AngularJs specific parts in the above HTML file. Specifically, here are the attributes that need attention -

    1. ng-app - This attribute enables AngularJs framework in the HTML element, it is specified in. AngularJs framework will only work in the elements (and their child elements recursively) on which this attribute is set. In our case, we have specified it in 'HTML' element so AngularJs library attributes/directives could be used on any element in our page. If we want to enabled AngularJs only for specific part of a page then it should be added to that element such as div.
    2. ng-controller - This directive attaches a controller to the element which in our case is "form" element. Specifying this directive will make AngularJs to call your controller that you provide in either <script> or a separate JS file. More details on this will be provided in javascript section.
    3. ng-show - This is a simple directive responsible to either show or hide an element based on the expression evaluation result. In our case, we have used it show the relevant error messages while hiding the others. '$dirty' is used to ensure that errors are shown after user has touched (focused or entered some value) the field. '$error' is used to check whether a particular type of validation fails for the entered value. There are some built in validation tokens, that can help in validating form: email, maxlength, minlength, url, etc.
    form-validation.css

    Next file to talk about is a css file that we have added to give our form a fine look. This is a simple CSS file without any angular or fancy stuff in it.

    form-validation.css
    input.ng-invalid.ng-dirty{
    	border: 1px solid red;
    }
    fieldset {
    	width: 100px;
    	margin: auto;
    }
    span{
    	color: red;
    }
    legend {
    	font-weight: bold;
    	font-size: 20px;
    	text-align: center; 
    }
    button {
    	margin-left: 110px;
    }
    body {
    	font:bold 12px Arial;
    }
    
    
    form-validation.js

    This is how our javascript file form-validation.js with AngularJs controller looks like -

    form-validation.js
    angular.module('myApp', [])
    .controller('Ctrl', function($scope) {
        $scope.username = /^\s*\w*\s*$/;
        $scope.pho_numbr = /^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/;
    });
    
    

    In this file, we specify the controller for module myApp. Module name needs to be same as what we have specified in ng-app directive. Similarly, controller name needs to be matched to the value of ng-controller directive value. $scope is used to bind/pass the data to view (HTML).

    Webpage Output in Browser

    This is how the HTML code above will be displayed in a browser with some validations shown in red color:

    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Posted By: Sumit Sain
    Published on: 2018-05-25 16:05:39

    Comment Form is loading comments...