Difference between $valid, $invalid, $pristine, and $dirty

Loading

In AngularJS, form validation uses built-in properties like $valid, $invalid, $pristine, and $dirty to track form and field states. These properties help manage form validation, error handling, and user input tracking.


1. Overview of Properties

PropertyDescription
$validTrue if the field/form has passed all validation checks.
$invalidTrue if at least one validation rule fails.
$pristineTrue if the field has not been modified by the user.
$dirtyTrue if the field has been modified by the user.

2. Understanding Each Property

$valid

  • Becomes true when the field or form passes all validation rules.
  • Used to check if a form is ready for submission.

Example: Check if input is valid

<input type="text" name="username" ng-model="user.name" required>
<p ng-show="myForm.username.$valid">✔ Valid Input</p>

If the field contains a value, the message appears.


$invalid

  • Becomes true if the field or form fails any validation rule.
  • Useful for showing error messages.

🔹 Example: Show error message when input is invalid

<form name="myForm">
<input type="email" name="email" ng-model="user.email" required>
<p ng-show="myForm.email.$invalid"> Invalid Email</p>
</form>

If the user enters an invalid email, the message appears.


$pristine

  • A field is pristine ($pristine = true) when it has not been touched.
  • Becomes false once the user modifies the field.

🔹 Example: Show message if the field is untouched

<input type="text" name="username" ng-model="user.name" required>
<p ng-show="myForm.username.$pristine"> Please enter your name</p>

The message disappears as soon as the user types something.


$dirty

  • A field is dirty ($dirty = true) when it has been modified.
  • Used to check if changes have been made.

🔹 Example: Show message when the field is changed

<input type="text" name="username" ng-model="user.name" required>
<p ng-show="myForm.username.$dirty"> You have modified this field</p>

Message appears when the user types something.


3. Summary Table

PropertyInitial StateChanges When…Use Case
$validfalseThe field passes validation.Check if input is correct.
$invalidtrueThe field fails validation.Show error messages.
$pristinetrueThe user types in the field.Track untouched fields.
$dirtyfalseThe user modifies the field.Detect modified fields.

4. Example: Full Form with Validation

<form name="userForm">
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required>

<p ng-show="userForm.email.$pristine"> Field is untouched</p>
<p ng-show="userForm.email.$dirty"> Field has been modified</p>
<p ng-show="userForm.email.$invalid"> Invalid email format</p>
<p ng-show="userForm.email.$valid"> Email is valid</p>
</form>

As the user types, messages update dynamically.

Leave a Reply

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