Angular Form Validation Example

Filed Under: AngularJS

In this post, we will see how Angular form validation works. Earlier we looked into angular form and controls.

Angular Form Validation

AngularJS makes it easy to handle client-side form validations without much effort. In next sections we will look into some Angular form validation example.

Angular Form Validation – input

Following are some of the basic angular form validation options available for an input field.

  1. required

  2. Adding required html5 tag to an input field validates whether the field is empty or not. This ensures that the field should have some value. The following syntax is used for required with input.

    
    <input type="text" required />
    

    AngularJS provides a ng-required directive to do the same thing. Using this directive you have the flexibility to set the input field should have a value or not.

    The following syntax is used to make sure that the input field should not be empty. We can set it to false if you do not want to restrict this.

    <input type="text" ng-required="true" />
  3. Minimum Length

  4. The directive ng-minlength is used to validate the minimum length of the input value.  This will make sure that the length of the entered value not less than the value set using ng-minlength directive.

    <input type="text" ng-minlength=10 />
  5. Maximum Length

  6. The directive ng-maxlength is used to validate the maximum length of the input value.  This will make sure that the length of the entered value is not more than the value set using ng-max length directive.

    <input type="text" ng-maxlength=20 />
  7. Pattern

  8. The ng-pattern directive is used to ensure that an input matches a regex pattern, the following syntax is used.

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

  10. We can set the input type to email to ensure that the input field is a valid email id.

    <input type="email" name="email" ng-model="user.email" />
  11. Number

  12. We can set the input type to number to ensure that the input field is a number.

    <input type="number" name="age" ng-model="user.age" />
  13. URL

  14. We can set the input type to url to ensure that the input field is a url.

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

Angular Form Validation Properties

Angular provides properties on forms to keep track of all its controls and nested forms as well as the state of them, such as being valid/invalid or dirty/pristine. The following table describes those properties and corresponding angular classes that help us to validate forms.

Property Class Description
$valid ng-valid Boolean True if all of the containing forms and controls are valid.
$invalid ng-invalid Boolean True if at least one containing control or form is invalid.
$pristine ng-pristine Boolean True if user has not interacted with the form yet.
$dirty ng-dirty Boolean True if user has already interacted with the form.
$touched ng-touched Boolean True if the input has been blurred.
$submitted ng-submit Boolean True if user has submitted the form even if its invalid.

Angular Form Validation Using CSS Classes

While handling forms angularJS adds specific classes to the form based upon their state. To allow styling of form as well as controls, ngModel adds these CSS classes:

  • ng-valid
  • ng-invalid
  • ng-pristine
  • ng-dirty
  • ng-touched
  • ng-untouched
  • ng-pending

The following example uses the following CSS to display validity of each form control.


<style type="text/css">
		.css-form input.ng-invalid.ng-touched {
			background-color: #FA787E;
		}

		.css-form input.ng-valid.ng-touched {
			background-color: #78FA89;
		}
	</style>

You have to add the required attribute with input field otherwise it will not validate correctly. You should also include novalidate attribute to disable the browser’s native form validation.


<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>AngularJS Form Validation</title>
	</head>

	<body ng-app="formApp">
		<div ng-controller="FormController">

			<form name="form" novalidate class="css-form">
				Name : <input type="text" ng-model="employee.name" required/><br />

				E-mail : <input type="email" ng-model="employee.email" required /><br />

				Role : <input type="radio" ng-model="employee.role" value="development" />Development
				<input type="radio" ng-model="employee.role" value="testing" />Testing<br /></br>

				<input type="button" ng-click="reset()" value="Reset" />

				<input type="submit" ng-disabled="form.$invalid" ng-click="save(employee)" value="Submit" />
			</form>

  			<p>Employee Form = {{employee | json}}</p>
  			<p>Master = {{master | json}}</p>
		</div>

	<style type="text/css">
		.css-form input.ng-invalid.ng-touched {
			background-color: #FA787E;
		}

		.css-form input.ng-valid.ng-touched {
			background-color: #78FA89;
		}
	</style>

	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

We have disabled the submit button if the form input is invalid. Following code shows how we used in our application.

<input type="submit" ng-disabled="form.$invalid" ng-click="save(employee)" value="Submit" />

The following script defines the controller used in our application.

app.js


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

	app.controller('FormController', function($scope) {
		$scope.master = {};

		$scope.save= function(employee) {
			$scope.master = angular.copy(employee);
		};

		$scope.reset = function() {
			$scope.employee = angular.copy($scope.master);
		};

		$scope.reset();
	});

You will see the following output on your browser. In the example both employee.name and employee.email are required, but are rendered with red background only after the input is out of focus.

Angular Form Validation Using $error property

AngularJS provides another property called $error , is an object hash, containing references to controls or forms with failing validators, where its keys are validation tokens (error names) and values are arrays of controls or forms that have a failing validator for given error name.
The following list shows the Built-in validation tokens:

  • email
  • max
  • maxlength
  • min
  • minlength
  • number
  • pattern
  • required
  • url
  • date
  • datetimelocal
  • time
  • week
  • month

The following angular form validation example shows form validation using $error property.
The following syntax is used to validate the input field using $error property – formName.inputFieldName.$error.validateToken

Angular Form Validation Example


<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>AngularJS Simple Form Demo</title>
	</head>

	<body ng-app="formApp">
		<div ng-controller="FormController">

			<form name="form" novalidate class="css-form">
				Name : <input type="text" ng-model="employee.name" name="empName" ng-required="true"/><br />
    				<div ng-show="form.$submitted || form.empName.$touched">
      					<span style="color:orange" ng-show="form.empName.$error.required">Please enter your name.</span>
    				</div>

				E-mail : <input type="email" name="empEmail" ng-model="employee.email" ng-required="true"/><br />
    				<div ng-show="form.$submitted || form.empEmail.$touched">
      					<span style="color:orange" ng-show="form.empEmail.$error.required">Please enter an email-id.</span>
      					<span style="color:red" ng-show="form.empEmail.$error.email">This is not a valid email.</span>
    				</div>

				Role : <input type="radio" ng-model="employee.role" value="development" />Development
				<input type="radio" ng-model="employee.role" value="testing" />Testing<br /></br>

				<input type="button" ng-click="reset()" value="Reset" />

				<input type="submit" ng-disabled="form.$invalid" ng-click="save(employee)" value="Submit" />
			</form>

  			<p>Employee Form = {{employee | json}}</p>
  			<p>Master = {{master | json}}</p>
		</div>

	<style type="text/css">
		.css-form input.ng-invalid.ng-touched {
			background-color: #FA787E;
		}

		.css-form input.ng-valid.ng-touched {
			background-color: #78FA89;
		}
	</style>

	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js


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

	app.controller('FormController', function($scope) {
		$scope.master = {};

		$scope.save= function(employee) {
			$scope.master = angular.copy(employee);
		};

		$scope.reset = function() {
			$scope.employee = angular.copy($scope.master);
		};

		$scope.reset();
	});

You will see the following output on your browser.

That’s all for angular form validation example, we will see more interesting posts in the coming series.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages