Validate input fields into AngularJS

AngularJS performs client-side form validation. AngularJS monitors the state of the form and input fields (input, text area, selection) and informs the user about the current state.

AngularJS also includes information about whether input fields have been touched, modified, or not.

Form input fields have the following states:

  • $untouched: Indicates that the field has not yet been touched.
  • $touched: Indicates that the field has been touched.
  • $pristine: This means the field has not been changed yet.
  • $dirty: Illustrates that the field has been changed.
  • $invalid: Indicates that the content of the field is not valid.
  • $valid: Indicates that the content of the field is valid.

Validate date field into angularJS

The angular.isDate() function in AngularJS is used to determine whether a date value is valid or not. Returns true if the reference is a date, false otherwise.

The below HTML code uses angular.isDate() function to check whether the input date is valid or not.

<!DOCTYPE html>
<html>

<head>
    <title>angular.isDate() function</title>
    
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
    </script>
</head>

<body ng-app="app" style="text-align:center">
    <h1 style="color:BLUE">CODEBUN</h1>
    <h2>angular.isDate()</h2>
    
    <div ng-controller="date">
        <b>Date:</b> {{ date }} <br><br>
            isDate: {{isDate}}
    </div>
    
    <!-- Script to uses angular.isDate() function -->
    <script>
        var app = angular.module("app", []);
        app.controller('date', ['$scope', function ($scope) {
            $scope.date = new Date;
            $scope.isDate = angular.isDate($scope.date)
        }]);
    </script>
</body>

</html>					

Validate password field into angularJS

Generally for a password to be valid it should be at least 8 characters long and should contain one number, one character, and one special character.

We will create a program using angularJS which uses the above criteria to check whether the password is valid or not and will generate the output true and false if the criteria match or not respectively.

HTML Code

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@1.11.3" data-semver="1.11.3" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script data-require="angularjs@1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
    <script data-require="ng-messages@1.3.16" data-semver="1.3.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-messages.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="demoApp" ng-controller="demoCtrl">
    <h1>Hello User!</h1>
    <form name="registerForm">
        <label>Password</label>
        <input type="password" ng-model="newUser.userPassword" name="userPassword" required ng-pattern="/^(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,20}$/">
        <div ng-messages="registerForm.userPassword.$error">
          <br>
          <div style="color:dodgerblue" ng-show="registerForm.userPassword.$error.required">Required!</div><br>
          <div style="color:orange" ng-show="!registerForm.userPassword.$valid">Password should be at least 8 characters
            long and should contain one number,one character and one special
            character</div>
          </div>
          <div style="color: green" ng-show="registerForm.userPassword.$valid">Yes</div>
      </form>
  </body>

</html>
JS file for the code 
// Code goes here

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

app.controller('demoCtrl',function($scope){
  $scope.newUser = {
    userPassword:''
  };
});

Initial interface

Interface after the password is input

Validate phone number into angularJS

For a phone number to be valid it must be of 10 digits.

Here below is the HTML and JS code using angularJS which helps to check whether the number is found to be validated or not.

HTML Code
<script src="https://code.angularjs.org/1.2.1/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div class="col-md-5">
    <div class="form-area" ng-controller="formCtrl">  
        <form role="form" name="inquiryForm" novalidate>
        <br style="clear:both">
                    <h3 style="margin-bottom: 25px; text-align: center;">Contact Form</h3>

                    
                    </div>
                    <div class="form-group">
                        <input name="contact" ng-model="contact" id="c_num" type="text" ng-required="true" ng-pattern="ph_numbr" autocomplete="off" placeholder="Contact Number" class="form-control">
            
            <span class="red-text" ng-if="inquiryForm.contact.$error.required && inquiryForm.contact.$dirty">Contact number is a required field</span>
            <span class="red-text" ng-show="inquiryForm.contact.$error.pattern">Please enter a valid 10 digit number</span>
            
                    </div>

            
        <button type="button" id="submit" name="submit" class="btn btn-primary pull-right" ng-disabled="inquiryForm.$invalid">Submit Form</button>
        </form>
    </div>
</div>
</div>
JS Code
var app = angular.module("myApp", []);
app.controller("formCtrl", ['$scope', function($scope) {
        $scope.ph_numbr = /^\+?\d{10}$/;
       
}]);

The output of the above codes

 

Validate email address into angularJS

For the email address to be valid it must contain “@gmail.com” after the username of the user.

Below is the HTML and JS code using angular which helps to find whether the email address is valid or not.

HTML Code

<sript src="https://code.angularjs.org/1.2.1/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div class="col-md-5">
    <div class="form-area" ng-controller="formCtrl">  
        <form role="form" name="inquiryForm" novalidate>
        <br style="clear:both">
                    <h3 style="margin-bottom: 25px; text-align: center;">Contact Form</h3>

                    <div class="form-group">
                        <input name="email" ng-model="email" id="eml" type="text" ng-pattern="eml_add" ng-required="true" autocomplete="off" placeholder="Email" class="form-control" >
            
            <span class="red-text" ng-if="inquiryForm.email.$error.required && inquiryForm.email.$dirty">Email is a required field</span>
            
            <span class="red-text" ng-show="inquiryForm.email.$error.pattern">Invalid Email</span>
                    
                    </div>

            
        <button type="button" id="submit" name="submit" class="btn btn-primary pull-right" ng-disabled="inquiryForm.$invalid">Submit Form</button>
        </form>
    </div>
</div>
</div>

JS Code

var app = angular.module("myApp", []);
app.controller("formCtrl", ['$scope', function($scope) {
       
        $scope.eml_add = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
}]);

Output of the above codes

 

Example1: With the help of this HTML code we are showcasing the thing that we use the ng-show directive to only show the error message if the field has not been modified yet AND the content present in the field is invalid.

<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body ng-app="">
<form name="form1">
<p>Name:
<input name="username" ng-model="username" required>
<span ng-show="form1.username.$pristine && form1.username.$invalid">
The name is required.</span>
</p>
<p>Address:
<input name="useraddress" ng-model="useraddress" required>
</p>
</form>
<p>We use the ng-show directive to only
show the error message if the field has
not modified yet AND content present in
the field is invalid.</p>
</body>
</html>

Output of the above code

As you can see that is emphasized on the field that the name is the required field.

For more information, we use the ng-show directive to only show the error message if the field has not been modified yet AND the content present in the field is invalid.

Custom Validation in AngularJS

To create a custom validation function, add a new directive to your application and handle the validation inside the function with certain arguments provided.

Example 2: Validate age is greater than or equal to 18 into AngularJS

Create a custom directive containing your own validation function and reference it with the app directive. The field will only be valid if the value is greater than or equal to 18.

<!DOCTYPE html>
<html>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<body ng-app="developapp">
<form name="form1">
Username:
<input name="username" required><br><br>
Age:
<input name="userage" ng-model="userage" required app-directive>
</form>

<p>The input's valid state is:</p>
<h1>{{form1.userage.$valid}}</h1>
<script>
var app = angular.module('developapp', []);
app.directive('appDirective', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attr, mCtrl) {
            function myValidation(value) {
                if (value >=18) {
                    mCtrl.$setValidity('charE', true);
                } else {
                    mCtrl.$setValidity('charE', false);
                }
                return value;
            }
            mCtrl.$parsers.push(myValidation);
        }
    };
});
</script>

<p>The input field must have
user age greater than 18 to be
considered valid for voting.</p>

</body>
</html>

When the input age is less than 18:

It will show false as you can see below.

When the input age is more than or equal to 18:

It will show true as you can see below in the image.