AngularJS > Forms & Validations

Input Validation basic in AngularJS

How to notify users if form input is valid using AngularJS?


AngularJS has inbuilt mechanism to identity the validity of the input element values and set css classes accordinlgy so that we can visually notify the user about it.

For that purpose, AngularJS model set one of following css classes to the input elements (note that AngularJS doens't have these classes defined so we need to define ourselves). All these css classes are set only after the element looses its focus (blurred)

  1. ng-valid - if the input value is valid
  2. ng-invalid - if the input value is invalid
  3. ng-pristine - if the element has not been interacted with ie. the element is in page load stage

In following code snippet, we have defined above css classes.

<style>
    .ng-valid{
        background-color:green;
        color:white;
    }
    .ng-invalid{
        background-color:red;
        color:black;
    }
    .ng-pristine{
        background-color:#9c914c;
    }    
</style>
<div ng-app>
    <h4>Valid values</h4>
    <p>String: <input type="text" ng-model="txtValue" required /> | {{ txtValue }}</p>
    <p>Email: <input type="email" ng-model="emailValue" required /> | {{ emailValue }}</p>
    <p>Number: <input type="number" ng-model="numberValue" required /> | {{ numberValue }}</p>
    <p>Date: <input type="date" ng-model="dateValue" required /> | {{ dateValue }}</p>
    <p>URL: <input type="url" ng-model="urlValue" required /> | {{ urlValue }}</p>
</div>

In the HTML block, we have following input elements and its css class is set by AngularJS as per their values

  1. Text box - to enter any stirng (ng-valid css class is set)
  2. Email - to enter email (if user enters wrong email, ng-invalid css class is set and the background of the text box becomes becomes red otherwise green because of ng-valid css class - ng-invalid class is set)
  3. Number - to enter number (if users enter alphabets, the background becomes red otherwise green - ng-valid css class is set)
  4. Date - to enter correct date (ng-valid class is set)
  5. URL - to enter correct url. In below image as we have not starting entering any data into Date text box so it's class is set as ng-pristine.

Output

Angular form input is valid

 Views: 16698 | Post Order: 47




Write for us






Hosting Recommendations