Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

Validate User Input

The ng-model directive can enforce type validation for application data, such as ensuring values are of type number, email, or required.

Example

<form ng-app=”” name=”myForm”>
  Email:
  <input type=”email” name=”myAddress” ng-model=”text”>
  <span ng-show=”myForm.myAddress.$error.email”>Not a valid e-mail address</span>
</form>

In the example above, the <span> will be shown only if the expression in the ng-show attribute evaluates to true.

If the property specified in the ng-model attribute does not exist, AngularJS will automatically create it for you.

Application Status

The ng-model directive can offer status indicators for application data, such as valid, dirty, touched, and error.

Example

<form ng-app=”” name=”myForm” ng-init=”myText = ‘[email protected]'”>
  Email:
  <input type=”email” name=”myAddress” ng-model=”myText” required>
  <h1>Status</h1>
  {{myForm.myAddress.$valid}}
  {{myForm.myAddress.$dirty}}
  {{myForm.myAddress.$touched}}
</form>

CSS Classes

The ng-model directive assigns CSS classes to HTML elements based on their status.

Example

<style>
input.ng-invalid {
  background-color: lightblue;
}
</style>
<body>

<form ng-app=”” name=”myForm”>
  Enter your name:
  <input name=”myName” ng-model=”myText” required>
</form>

The ng-model directive adds or removes the following classes based on the status of the form field:

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine