---
title: "Form validation in AngularJS"  
description: "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."  
author: "Ravi Vishwakarma"  
published: 2024-06-24  
updated: 2024-06-24  
canonical: https://www.mindstick.com/articles/336202/form-validation-in-angularjs  
category: "angular js"  
tags: ["web development", "angular js", "front-end development"]  
reading_time: 4 minutes  

---

# Form validation in AngularJS

[**Form validation**](https://www.mindstick.com/articles/335844/form-validation-and-request-submission-in-angular-js) 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](https://www.mindstick.com/forum/1973/custom-validation-attribute).

#### Built-in Validation Directives

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

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

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

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

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

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

**ng-pattern**: Specifies a [regular expression](https://www.mindstick.com/forum/12854/how-to-solve-regular-expression-for-validating-id-in-c-sharp-asp-dot-net) that the input field's value must match.

```javascript
<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.

```javascript
<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:

```html
<!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](https://www.mindstick.com/blog/11464/improve-your-understanding-of-web-applications).

#### Benefits

- **Improved [User Experience](https://yourviews.mindstick.com/view/87076/explore-your-career-in-user-experience-design)**: Real-time feedback on form inputs helps users correct errors immediately.
- **Increased [Data Integrity](https://www.mindstick.com/forum/160197/what-is-the-normalization-in-sql-server-explain-its-impact-on-data-integrity-and-performance)**: Ensures that data submitted to the server meets the specified [validation rules](https://www.mindstick.com/interview/34052/custom-validation-rules-and-validation-messages-in-knockout).
- **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](https://www.mindstick.com/forum/160789/how-to-handle-complex-data-binding-scenarios-in-knockout-js) 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](https://answers.mindstick.com/qa/113956/how-does-the-syntax-of-programming-languages-impact-their-learning-curve-for-beginners)**: 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](https://answers.mindstick.com/qa/116085/which-osi-layer-ensures-data-encryption-compression-and-translation) integrity, making it a vital feature for web applications.

---

Original Source: https://www.mindstick.com/articles/336202/form-validation-in-angularjs

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
