Open In App

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

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Steps to configure the AngularJS Application

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

Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir form-validate
cd form-validate

Step 2: Create the index.html file which will have the entire behavior of the application including the styling, AngularJS code, and structural HTML code.

Approaches for Preventing form submission when input validation fails

We will understand the above-mentioned approaches through the illustration.

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.

Below is the detailed information on the inbuilt validations used:

  • Username Field
    • required: This makes sure that the username field is required and must not be submitted empty
    • ng-minlength=”3″: This defines a minimum length of 3 characters for the username field.
  • Email Field
    • required: Make sure that the email field is required and must not be left empty.
    • ng-pattern=”/^.+@.+\..+$/”: Uses a regular expression pattern to check if the entered email address has a valid format.
  • Mobile Number Field
    • ng-pattern=”/^[0-9]{10}$/”: Uses a regular expression pattern to validate that the mobile number consists of exactly 10 digits.
    • placeholder: Provides a placeholder to guide users on the expected format.

Example: Below is an example that showcases the preventing form submission when input validation fails in AngularJS using AngularJS Built-in 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: #fff;
            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;
        }
  
        input.ng-invalid {
            border-color: #f00;
        }
  
        .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>GeeksforGeeks</h1>
        <h3>
              Approach 1: Using AngularJS Built-in 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" required 
                       ng-minlength="3">
                <span class="error"
                      ng-show="myForm.username.$dirty">
                    <span ng-show="myForm.username.$error.required">
                        Username is required.</span>
                    <span ng-show="myForm.username.$error.minlength">
                        Username must be at least 3 characters long.
                    </span>
                </span>
            </div>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="email"
                       id="email" 
                       name="email" 
                       ng-model="user.email" required 
                       ng-pattern="/^.+@.+\..+$/">
                <span class="error" ng-show="myForm.email.$dirty">
                    <span ng-show="myForm.email.$error.required">
                        Email is required.
                    </span>
                    <span ng-show="myForm.email.$error.pattern">
                        Invalid email address.
                    </span>
                </span>
            </div>
            <div class="form-group">
                <label for="mobile">Mobile Number:</label>
                <input type="tel" 
                       id="mobile" 
                       name="mobile" 
                       ng-model="user.mobile" 
                       ng-pattern="/^[0-9]{10}$/"
                       placeholder="Enter 10-digit mobile number" required>
                <span class="error" 
                      ng-show="myForm.mobile.$dirty">
                    <span ng-show="myForm.mobile.$error.required">
                        Mobile number is required.
                    </span>
                    <span ng-show="myForm.mobile.$error.pattern">
                        Please enter a valid
                        10-digit mobile number.
                    </span>
                </span>
            </div>
            <button type="submit" 
                    ng-disabled="myForm.$invalid">
                  Submit
              </button>
        </form>
        <div ng-show="submitted">
            <h2>Form submitted successfully!</h2>
        </div>
    </div>
    <script src=
    </script>
    
    <script>
        var app = angular.module('formApp', []);
        app.controller('formController', function ($scope) {
            $scope.user = {};
            $scope.submitted = false;
            $scope.submitForm = function () {
                if ($scope.myForm.$valid) {
                    alert('Form submitted successfully!');
                    $scope.submitted = true;
                }
            };
        });
    </script>
</body>
  
</html>


Output:

Val1

Using Custom Controller-Based Validation

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>GeeksforGeeks</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=
    </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:

Val2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads