πŸ“AngularJS Forms & User Input
Estimated reading: 5 minutes 25 views

βœ… AngularJS Form Validation – Complete Guide (2025)

🧲 Introduction – Why Learn AngularJS Form Validation?

Form validation is essential to ensuring data integrity, user experience, and security. In AngularJS, form validation is built-in and handled through powerful directives like required, ng-pattern, and ng-minlength, combined with AngularJS’s automatic form state tracking via properties like $valid, $dirty, and $touched.

AngularJS allows:

  • Live validation as users type
  • Clean error messaging based on state
  • Disabling form submission if invalid

🎯 In this guide, you’ll learn:

  • How AngularJS tracks form state and validity
  • How to use built-in validation directives
  • How to display custom error messages
  • Best practices and real-world examples

πŸ“‹ Form Validation Essentials in AngularJS

AngularJS tracks every form and input field using $-prefixed properties such as:

PropertyDescription
$validTrue if field/form passes all rules
$invalidOpposite of $valid
$dirtyField has been modified
$pristineField untouched since load
$touchedField has been focused and blurred
$untouchedField has not been blurred yet
$submittedForm has been submitted

Each <form> and <input> with a name attribute automatically gets a reference in the scope.


πŸ› οΈ Example – Basic Login Form with Validation

<form name="loginForm" ng-submit="submit()" novalidate>
  <input type="email" name="email" ng-model="user.email" required>
  <span ng-show="loginForm.email.$touched && loginForm.email.$invalid">
    Please enter a valid email.
  </span>

  <input type="password" name="password" ng-model="user.password" required ng-minlength="6">
  <span ng-show="loginForm.password.$dirty && loginForm.password.$invalid">
    Password must be at least 6 characters.
  </span>

  <button type="submit" ng-disabled="loginForm.$invalid">Login</button>
</form>
$scope.user = {};
$scope.submit = function() {
  alert("Submitted!");
};

βœ… AngularJS automatically disables the button until the form is valid.


πŸ” Commonly Used Validation Directives

DirectivePurposeExample
requiredField must not be empty<input required>
ng-patternField must match a regex<input ng-pattern="/^[0-9]{10}$/">
ng-minlengthMinimum length of characters<input ng-minlength="5">
ng-maxlengthMaximum allowed length<input ng-maxlength="20">
type="email"Email-specific validation<input type="email">
type="number"Numeric-only validation<input type="number">

πŸ“˜ Error Handling with $error Object

Every field’s validation state is available through its $error object.

<span ng-show="loginForm.email.$error.required">Email is required.</span>
<span ng-show="loginForm.email.$error.email">Email is not valid.</span>

πŸ” You can use $error to show specific messages for each type of validation failure.


πŸ“¦ Grouping Validations in Custom Logic

<div ng-if="myForm.username.$touched">
  <p ng-show="myForm.username.$error.required">Username is required.</p>
  <p ng-show="myForm.username.$error.minlength">Minimum 4 characters required.</p>
</div>

πŸ§ͺ Custom Validator with $setValidity

AngularJS also supports custom validation through directive controllers.

app.directive('startsWithA', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelCtrl) {
      ngModelCtrl.$validators.startsWithA = function(value) {
        return /^a/i.test(value);
      };
    }
  };
});
<input name="title" ng-model="book.title" starts-with-a>
<span ng-show="myForm.title.$error.startsWithA">
  Must start with "A"
</span>

βœ… This custom validator ensures input begins with letter A (case-insensitive).


🧠 Real-World Use Case – Signup Form with Validations

<form name="signupForm" ng-submit="register(user)" novalidate>
  <input ng-model="user.username" name="username" required ng-minlength="4">
  <span ng-show="signupForm.username.$error.required">Required</span>
  <span ng-show="signupForm.username.$error.minlength">Too short</span>

  <input type="email" ng-model="user.email" name="email" required>
  <span ng-show="signupForm.email.$invalid">Invalid email</span>

  <input type="password" ng-model="user.password" name="password" required>
  <button ng-disabled="signupForm.$invalid">Register</button>
</form>

βš™οΈ Best Practices

βœ”οΈ Use novalidate to disable native HTML5 validation
βœ”οΈ Always name your forms and inputs to access their states
βœ”οΈ Use $touched, $dirty, and $error to control validation feedback
βœ”οΈ Centralize error messages to reduce repetition
βœ”οΈ Avoid over-validationβ€”only validate what’s necessary


πŸ“Œ Summary – Recap & Next Steps

AngularJS provides powerful, declarative validation out of the box, which enables developers to build reliable, user-friendly forms with minimal effort.

πŸ” Key Takeaways:

  • Validation happens automatically using built-in directives
  • $valid, $invalid, and $error track input state
  • Error messages are shown using $touched, $dirty, and $error
  • Custom validation can be implemented via directives

βš™οΈ Real-world Relevance:
Essential for user signup, login, feedback forms, admin panels, data entry, checkout forms, and all modern web app forms.


❓ FAQ – AngularJS Form Validation


❓ What is the role of novalidate in AngularJS forms?
βœ… It disables the browser’s native HTML5 validation so that AngularJS handles it completely.


❓ How do I show a message only when a field is invalid and touched?
βœ… Use:

<span ng-show="form.field.$touched && form.field.$invalid">Invalid input</span>

❓ Can I create custom validation logic in AngularJS?
βœ… Yes, by using $setValidity in a directive linked to ngModel.


❓ What’s the difference between $dirty and $touched?
βœ… $dirty tracks whether the field was modified. $touched tracks if the user focused and blurred the field.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

βœ… AngularJS Form Validation

Or Copy Link

CONTENTS
Scroll to Top