Episode 22 of 25

Form Validation Part 1

Learn AngularJS built-in form validation — required, pattern, min/max, and validation states.

AngularJS provides powerful built-in form validation that works without any JavaScript.

Basic Validation

<form name="myForm" ng-submit="submitForm()" novalidate>
    <div>
        <label>Name:</label>
        <input type="text" name="userName" ng-model="user.name"
               required ng-minlength="3" ng-maxlength="20">
    </div>

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

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

Validation Properties

AngularJS adds properties to the form and its inputs:

myForm.$valid      // true if all fields are valid
myForm.$invalid    // true if any field is invalid
myForm.$pristine   // true if no field has been modified
myForm.$dirty      // true if any field has been modified

myForm.userName.$valid
myForm.userName.$invalid
myForm.userName.$pristine
myForm.userName.$dirty
myForm.userName.$touched    // true if field has been blurred
myForm.userName.$error      // object with error details

Showing Error Messages

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

<div ng-show="myForm.userName.$touched">
    <p ng-show="myForm.userName.$error.required" class="error">
        Name is required.
    </p>
    <p ng-show="myForm.userName.$error.minlength" class="error">
        Name must be at least 3 characters.
    </p>
</div>

CSS Classes

AngularJS automatically adds CSS classes:

.ng-valid { }
.ng-invalid { border: 1px solid red; }
.ng-pristine { }
.ng-dirty { }
.ng-touched { }
/* Style invalid fields after user interaction */
input.ng-invalid.ng-touched {
    border: 2px solid #e74c3c;
}
input.ng-valid.ng-touched {
    border: 2px solid #2ecc71;
}