How to use Custom Controller-Based Validation In Angular

In this approach, rather than relying on the inbuilt validation utilities, we have defined our own custom controller-based validation functions. Here, for each field of Username, Password, and Confirm Password, we have used the custom controller function. 

Below is the explanation of the custom controllers used:

  • validateUsername(): This checks the minimum length of 5 characters for the username field. If it is not satisfied then the error message is been displayed dynamically.
  • validatePassword(): This checks whether the entered password by the user is at least 8 characters long. If not, then the error message is been shown and the form is not submitted till the input is as per the validation.
  • validateConfirmPassword(): This is used to validate the Confirm Password field. This checks whether the password entered here is the same as the Password field above.

Example: Below is an example that demonstrates the preventing form submission when input validation fails in AngularJS using Custom Controller-Based Validation.

HTML




<!DOCTYPE html>
<html ng-app="formApp">
  
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            text-align: center;
        }
  
        .container {
            background-color: #f4f4f4;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            width: 400px;
            margin: 0 auto;
            padding: 20px;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            color: rgb(0, 0, 0);
        }
  
        form {
            margin-top: 20px;
        }
  
        .form-group {
            margin: 10px 0;
        }
  
        label {
            display: block;
            text-align: left;
            margin-bottom: 5px;
            font-weight: bold;
        }
  
        input {
            width: 90%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }
  
        .error {
            color: #f00;
            font-size: 14px;
            text-align: left;
        }
  
        button {
            background-color: #3498db;
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            font-size: 18px;
            cursor: pointer;
        }
  
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
  
        button:hover {
            background-color: #2e87d3;
        }
    </style>
</head>
  
<body ng-controller="formController">
    <div class="container">
        <h1>w3wiki</h1>
        <h3>
              Approach 2: Using Custom Controller-Based Validation
          </h3>
        <form name="myForm" 
              ng-submit="submitForm()" novalidate>
            <div class="form-group">
                <label for="username">Username:</label>
                <input type="text" 
                       id="username"
                       name="username" 
                       ng-model="user.username" 
                       ng-change="validateUsername()" required>
                <span class="error"
                      ng-show="usernameError">
                    {{ usernameError }}
                  </span>
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="password"
                       id="password"
                       name="password" 
                       ng-model="user.password"
                       ng-change="validatePassword()" required>
                <span class="error" 
                      ng-show="passwordError">
                    {{ passwordError }}
                  </span>
            </div>
            <div class="form-group">
                <label for="confirmPassword">
                      Confirm Password:
                  </label>
                <input type="password"
                       id="confirmPassword"
                       name="confirmPassword" 
                       ng-model="user.confirmPassword"
                       ng-change="validateConfirmPassword()" required>
                <span class="error" 
                      ng-show="confirmPasswordError">
                    {{ confirmPasswordError }}
                  </span>
            </div>
            <button type="submit" 
                    ng-disabled="formInvalid">
                  Register
              </button>
        </form>
    </div>
    
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
    </script>
    
    <script>
        var app = angular.module('formApp', []);
        app.controller('formController', function ($scope) {
            $scope.user = {};
            $scope.usernameError = '';
            $scope.passwordError = '';
            $scope.confirmPasswordError = '';
            $scope.formInvalid = true;
            $scope.submitForm = function () {
                if (!$scope.usernameError && !$scope.passwordError
                    && !$scope.confirmPasswordError) {
                    alert('Registration successful!');
                }
            };
            $scope.validateUsername = function () {
                $scope.usernameError = '';
                if (!$scope.user.username) {
                    $scope.usernameError = 'Username is required.';
                } else if ($scope.user.username.length < 5) {
                    $scope.usernameError
                     'Username must be at least 5 characters long.';
                }
                $scope.validateForm();
            };
            $scope.validatePassword = function () {
                $scope.passwordError = '';
                if (!$scope.user.password) {
                    $scope.passwordError
                      'Password is required.';
                } else if ($scope.user.password.length < 8) {
                    $scope.passwordError
                      'Password must be at least 8 characters long.';
                }
                $scope.validateConfirmPassword();
            };
            $scope.validateConfirmPassword = function () {
                $scope.confirmPasswordError = '';
                if (!$scope.user.confirmPassword) {
                    $scope.confirmPasswordError =
                      'Confirm Password is required.';
                } else if (
                  $scope.user.confirmPassword !== $scope.user.password) {
                    $scope.confirmPasswordError
                      'Passwords do not match.';
                }
                $scope.validateForm();
            };
            $scope.validateForm = function () {
                $scope.formInvalid = 
                  !!$scope.usernameError || !!$scope.passwordError
                    || !!$scope.confirmPasswordError;
            };
        });
    </script>
</body>
  
</html>


Output:



How to prevent form submission when input validation fails in AngularJS ?

Validation of fields is an important process while developing a dynamic web application. In terms of security, validation is an important concept. We pass the data from the client side through input fields to the server. If any of the fields is not validated properly and the user sends any irrelevant data then there can be cause of different security attack. So before submitting any of the forms in AngularJS, the validation of the fields should be done. We can validate the fields by setting the regex expressions, character limits, and more validations.

In this article, we will see how we can prevent form submission when input validation fails in AngularJS.

Similar Reads

Steps to configure the AngularJS Application

The below steps will be followed to configure the AngularJS Application:...

Approaches for Preventing form submission when input validation fails

Table of Content Using AngularJS Built-in Validation Using Custom Controller-Based Validation...

Using AngularJS Built-in Validation

In this approach, we are using the AngularJS built-in validation utilities. Here, we are validating the Username, Email, and Mobile Number fields. We have used the inbuilt validation fields like, required, ng-minlength, ng-pattern, placeholder, etc to provide the validation to the fields....

Using Custom Controller-Based Validation

...