Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

AngularJS Validation

AngularJS is capable of validating input data.

Form Validation

AngularJS provides client-side form validation.

It tracks the state of forms and input fields (input, textarea, select), allowing you to inform users about their current status.

AngularJS also retains information about whether the fields have been touched or modified.

You can utilize standard HTML5 attributes for input validation or create your own custom validation functions.

Client-side validation alone cannot ensure the security of user input; server-side validation is also essential.

Required

Utilize the HTML5 required attribute to indicate that the input field must be completed.

Example

The input field is mandatory.

<form name=”myForm”>
  <input name=”myInput” ng-model=”myInput” required>
</form>

<p>The input’s valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>

E-mail

Use the HTML5 type=“email” attribute to indicate that the value must be an email address.

Example

The input field must contain an email address.

<form name=”myForm”>
  <input name=”myInput” ng-model=”myInput” type=”email”>
</form>

<p>The input’s valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>

Form State and Input State

AngularJS continuously updates the state of both the form and its input fields.

Input fields can have the following states:

  • $untouched: The field has not been interacted with yet.
  • $touched: The field has been interacted with.
  • $pristine: The field has not been changed yet.
  • $dirty: The field has been modified.
  • $invalid: The content of the field is invalid.
  • $valid: The content of the field is valid.

These are properties of the input field and can be either true or false.

Forms can have the following states:

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

These are properties of the form and can also be either true or false.

You can use these states to provide meaningful feedback to the user. For example, if a field is required and left blank, you should display a warning to the user.

Example

Display an error message if the field has been touched and is empty.

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