AngularJS Form Validation

AngularJS can validate input data.

Form Validation

AngularJS provides client-side form validation.

AngularJS monitors the status of forms and input fields (input, textarea, select) and allows you to notify users of the current status.

AngularJS also includes information about whether they have been touched or modified.

You can use standard HTML5 attributes to validate input, or create your own validation function.

Client-side validation cannot protect user input alone. Server-side validation is also necessary.

required

Using HTML5 attributes required The specified input field must be filled in:

instance

This input field is required:

<form name="myForm">  
  <input name="myInput" ng-model="myInput" required>  
</form>  
<p>The valid status of the input is:</p>  
<h1>{{myForm.myInput.$valid}}</h1>

Try It Yourself

email

Using HTML5 type email The specified value must be an email:

instance

This input field must be an email:

<form name="myForm">  
  <input name="myInput" ng-model="myInput" type="email">  
</form>  
<p>The valid status of the input is:</p>  
<h1>{{myForm.myInput.$valid}}</h1>

Try It Yourself

Form Status and Input Status

AngularJS continuously updates the status of forms and input fields.

The input field has the following status:

  • $untouched This field has not been touched
  • $touched This field has been touched
  • $pristine This field has not been modified
  • $dirty This field has been modified
  • $invalid Field content is invalid
  • $valid Field content is valid

They are all properties of the input field, either true or false.

The form has the following status:

  • $pristine No fields have been modified yet
  • $dirty One or more fields have been modified
  • $invalid The form content is invalid
  • $valid The form content is valid
  • $subscribed The form has been submitted

They are all properties of the form, which can be either true or false.

You can use these states to display meaningful messages to the user. For example, if a field is required and the user leaves it blank, a warning should be issued to the user:

instance

If the field has been touched and is empty, display an error message:

<input name="myName" ng-model="myName" required>  
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is a required field.</span>

Try It Yourself

CSS Classes

AngularJS adds CSS classes to forms and input fields based on their status.

The following classes have been added to or removed from the input field:

  • ng-untouched This field has not been touched
  • ng-touched This field has been touched
  • ng-pristine This field has not been modified
  • ng-dirty This field has been modified
  • ng-valid Field content is valid
  • ng-invalid Field content is invalid
  • ng-valid-key Validate one key at a time. For example:ng-valid-requiredIt is very useful when there are multiple required validations.
  • ng-invalid-key For example:ng-invalid-required

The following classes have been added to or removed from the form:

  • ng-pristine No fields have been modified yet
  • ng-dirty One or more fields have been modified
  • ng-valid The form content is valid
  • ng-invalid The form content is invalid
  • ng-valid-key Validate one key at a time. For example:ng-valid-requiredIt is very useful when there are multiple required validations.
  • ng-invalid-key For example:ng-invalid-required

If the value represented by the class is falseThen these classes will be removed.

Please add styles to these classes to provide a better and more intuitive user interface for your application.

instance

Apply standard CSS styles:

<style>
input.ng-invalid {
  background-color: pink;
};
input.ng-valid {
  background-color: lightgreen;
};
</style>

Try It Yourself

You can also set the form's styles.

instance

Apply styles to both the unmodified (original) form and the modified form:

<style>
form.ng-pristine {
  background-color: lightblue;
};
form.ng-dirty {
  background-color: pink;
};
</style>

Try It Yourself

Custom Validation

Creating your own validation function requires some skill; you must add a new directive to the application and use certain specified parameters to handle the validation inside the function.

instance

Create your own directive, containing a custom validation function, and use it my-directive reference it.

The field is valid only when the value contains the character "e":

<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        if (value.indexOf("e") > -1) {
          mCtrl.$setValidity('charE', true);
        } else {
          mCtrl.$setValidity('charE', false);
        };
        return value;
      };
      mCtrl.$parsers.push(myValidation);
    };
  };
});
</script>

Try It Yourself

Example Explained:

In HTML, the new directive will be created by using the attribute my-directive to reference.

In JavaScript, we first add a name myDirective new directive.

Remember, when naming a directive, you must use camelCase naming, such as myDirective, but when calling it, you must use hyphenated names, such as my-directive.

Then, return an object specifying what we need ngModel, namely ngModelController.

Create a link function that accepts some parameters, among which the fourth parameter mCtrl is ngModelController.

Then specify a function, in this example named myValidation, which accepts a parameter, the value of the input element.

Test whether the value contains the letter "e" and set the validity of the model controller to true or false.

Finally,mCtrl.$parsers.push(myValidation); will be myValidation Functions are added to an array of other functions, which will be executed each time the input value changes.

Validation Example

<!DOCTYPE html>
<html>
<script src="https://cdn.staticfile.net/angular.js/1.6.9/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<form ng-app="myApp"  ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Username:<br>
  <input type="text" name="user" ng-model="user" required>
  <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
  <span ng-show="myForm.user.$error.required">Username is required.</span>
  </span>
</p>
<p>Email:<br>
  <input type="email" name="email" ng-model="email" required>
  <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
  <span ng-show="myForm.email.$error.required">Email is required.</span>
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>
  </span>
</p>
<p>
  <input type="submit"
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {}}
  $scope.user = 'Bill Gates';
  $scope.email = 'bill.gates@gmail.com';
});
</script>
</body>
</html>

Try It Yourself

HTML Form Attribute novalidate Used to disable the default browser validation.

Example Explanation:

AngularJS Directives ng-model Bind the input element to the model.

The model object has two properties:user and email.

because ng-showonly when user or email is $dirty and $invalid spans with color:red will be displayed.