Validating email and phone number fields in AngularJS

Loading

What You’ll Learn

How to validate email and phone number fields in AngularJS
Using built-in directives (ng-pattern, required, type="email")
Displaying error messages dynamically
Best practices for form validation


1️⃣ Validating an Email Field in AngularJS

AngularJS provides built-in email validation using type="email".

Example: Email Validation

<div ng-app="myApp" ng-controller="FormController">
<form name="userForm" novalidate>

<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required />

<span class="error" ng-show="userForm.email.$touched && userForm.email.$invalid">
Enter a valid email address.
</span>

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>

How It Works:

  • type="email" ensures only valid emails can be entered.
  • required makes the field mandatory.
  • $touched && $invalid prevents error messages from showing until the user interacts with the field.

2️⃣ Validating a Phone Number Using ng-pattern

Since AngularJS does not have built-in phone validation, we use ng-pattern to enforce a format.

Example: Phone Number Validation

<label>Phone Number:</label>
<input type="text" name="phone" ng-model="user.phone" required
ng-pattern="/^\d{10}$/" />

<span class="error" ng-show="userForm.phone.$touched && userForm.phone.$invalid">
Enter a valid 10-digit phone number.
</span>

How It Works:

  • ng-pattern="/^\d{10}$/" only allows 10-digit numbers.
  • required ensures the field cannot be left empty.
  • $touched && $invalid prevents errors until the user interacts with the field.

3️⃣ Full Example: Email & Phone Validation

HTML Form

<div ng-app="myApp" ng-controller="FormController">
<form name="userForm" ng-submit="submitForm()" novalidate>

<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required />
<span class="error" ng-show="userForm.email.$touched && userForm.email.$invalid">
Enter a valid email.
</span>

<label>Phone Number:</label>
<input type="text" name="phone" ng-model="user.phone" required
ng-pattern="/^\d{10}$/" />
<span class="error" ng-show="userForm.phone.$touched && userForm.phone.$invalid">
Enter a valid 10-digit phone number.
</span>

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>

AngularJS Controller

var app = angular.module("myApp", []);

app.controller("FormController", function ($scope) {
$scope.user = {}; // Form model

$scope.submitForm = function () {
if ($scope.userForm.$valid) {
alert("Form submitted successfully!");
}
};
});

Leave a Reply

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