articles

Home / DeveloperSection / Articles / Form validation in AngularJS

Form validation in AngularJS

Form validation in AngularJS

Ravi Vishwakarma 161 24-Jun-2024

Form validation is a key feature in AngularJS that ensures the data entered by the user conforms to the expected format before it is processed. AngularJS provides a robust mechanism for validating forms and fields, including built-in validation directives and support for custom validation.

Built-in Validation Directives

ng-required: Specifies that an input field must be filled out before submitting the form.

<input type="text" ng-model="user.name" ng-required="true">

ng-minlength: Sets the minimum number of characters required in an input field.

<input type="text" ng-model="user.name" ng-minlength="3">

ng-maxlength: Sets the maximum number of characters allowed in an input field.

<input type="text" ng-model="user.name" ng-maxlength="10">

ng-pattern: Specifies a regular expression that the input field's value must match.

<input type="text" ng-model="user.email" ng-pattern="/^[a-z]+@[a-z]+\.[a-z]{2,3}$/">

ng-change: Specifies an expression to evaluate when the value of an input field changes.

<input type="text" ng-model="user.name" ng-change="validateName()">

Example of Form Validation

Below is an example AngularJS application that demonstrates form validation using built-in directives:

<!doctype html>
<html lang="en" data-ng-app="myApp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AngularJS Todo List</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <!-- Angurr JS CDN  -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"
        integrity="sha512-KZmyTq3PLx9EZl0RHShHQuXtrvdJ+m35tuOiwlcZfs/rE7NZv29ygNA8SFCkMXTnYZQK2OX0Gm2qKGfvWEtRXA=="
        crossorigin="anonymous" referrerpolicy="no-referrer">
        </script>


    <style>
        .ng-invalid.ng-touched {
            border-color: red;
        }

        .ng-valid.ng-touched {
            border-color: green;
        }
    </style>


</head>

<body>
    <div class="container" ng-app="myApp" ng-controller="MySimpleController">
        <h2>AngularJS Form</h2>
        <hr>
        <!-- Create a form  -->
        <form name="userForm" class="row g-3" accept="" method="" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- Create a field for name model --> <div class="col-12"> <label class="form-label fw-bold">Name</label> <input type="text" id="name" name="name" ng-model="user.name" ng-minlength="3" ng-maxlength="20" class="form-control" placeholder="Name" autofocus="true" ng-pattern="/^[a-zA-Z0-9._-]+$/" required /> <p class="text-danger"> <span ng-show="userForm.name.$error.required && userForm.name.$touched">Name is required.</span> <span ng-show="userForm.name.$error.minlength">Name is too short.</span> <span ng-show="userForm.name.$error.maxlength">Name is too long.</span> <span ng-show="userForm.name.$error.pattern">Invalid name format.</span> </p> </div> <!-- Create a filed for email model --> <div class="col-12"> <label class="form-label fw-bold">Email</label> <input type="email" ng-model="user.email" class="form-control" placeholder="Email" autofocus="true" required /> <p class="text-danger"> <span ng-show="userForm.email.$error.required && userForm.email.$touched">Email is required.</span> <span ng-show="userForm.email.$error.email">Invalid email address.</span> </p> </div> <!-- Create a field for age model --> <div class="col-12"> <label class="form-label fw-bold">Age</label> <input type="number" id="age" name="age" ng-model="user.age" min="0" max="120" class="form-control" placeholder="Age" autofocus="true" required /> <p class="text-danger"> <span ng-show="userForm.age.$error.required && userForm.age.$touched">Age is required.</span> <span ng-show="userForm.age.$error.min">Age must be at least 0.</span> <span ng-show="userForm.age.$error.max">Age must be at most 120.</span> </p> </div> <!-- Create a field for about model --> <div class="col-12"> <label class="form-label fw-bold">About</label> <textarea type="text" id="about" name="about" ng-model="user.about" class="form-control" placeholder="About" autofocus="true" required></textarea> <p class="text-danger"> <span ng-show="userForm.about.$error.required && userForm.about.$touched">About is required.</span> </p> </div> <div class="col-12"> <!-- <button class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button> --> <button class="btn btn-primary" >Submit</button> <div> </form> </div> <script> var app = angular.module('myApp', []); app.controller('MySimpleController', function ($scope) { $scope.user = { name: '', email: '', age: null, about: null }; $scope.checkUsername = function (value) { // Custom validation logic if (value) { var isValid = value.match(/^[a-zA-Z0-9._-]+$/); return isValid ? true : false; } return false; }; $scope.submitForm = function (isValid) { if (isValid) { // Process form data alert('Form is valid!'); } }; }); </script> </body> </html>

AngularJS provides a comprehensive set of built-in directives for form validation, including ng-required, ng-minlength, ng-maxlength, ng-pattern, and ng-change. These directives allow developers to ensure that user input meets specific criteria before it is processed, enhancing the robustness and reliability of web applications.

Benefits

  • Improved User Experience: Real-time feedback on form inputs helps users correct errors immediately.
  • Increased Data Integrity: Ensures that data submitted to the server meets the specified validation rules.
  • Custom Validation: Allows the creation of custom validation rules to meet specific requirements.
  • Declarative Syntax: This makes it easy to add validation rules directly in the HTML, improving code readability.

Pros

  • Built-in Support: AngularJS provides a wide range of built-in validation directives.
  • Real-time Feedback: Validation messages can be shown as the user types, providing instant feedback.
  • Customizability: Custom validation can be implemented to handle complex scenarios.

Cons

  • Complexity: Managing complex forms with many validation rules can become cumbersome.
  • Performance: Extensive use of validation directives can impact performance, especially in large forms.
  • Learning Curve: Developers need to understand how AngularJS validation works, which can be challenging for beginners.

Overall, form validation in AngularJS enhances the user experience and ensures data integrity, making it a vital feature for web applications.

 


Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By