Validations in AngularJS

Validations in AngularJS: With Angular controls and forms, the input can be validated. This means that they offer the user’s validation services and are capable of notifying the users in case they receive invalid data. User input cannot be secured only on the client-side of the application. This explains the necessity for server-side validation.

Validations in AngularJS Example

Consider the code given below.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js></script>
<body>
<h2>An example of Validation </h2>
<form ng-app="myApplication" ng-controller="validateCtrl"
name="form" novalidate>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="form.user.
$dirty && form.user.$invalid">
<span ng-show="form.user.$error.required">Username must be provided.as/span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ngmodel="email" required>
<span style="color:red" ng-show="form.email.
$dirty && form.email.$invalid">
<span ng-show="form.email.$error.required">Email is required.</span>
<span ng-show="form.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="form.user.$dirty && form.user.$invalid ||
form.email.$dirty && form.email.$invalid">
</p>
</form>
<script>
var application = angular.module(myApplication",[]);
application.controller('validateCtrl', functions($scope) {
$scope.user = John Joel';
$scope.email john.joel@gmail.com
});
</script>
</body>
</html>

The program can be written Just as we have written it above, and then executed.

Validations in AngularJS Example Output

Angular JS Validation Example Output

The Mandatory Fields

As shown in the output, we have created a form with two fields where the data can be provided. These are the fields that we have validated. The email has to be validated so that one enters a valid one. The username also has to be provided. If you do not specify the values for these attributes, then you will observe the following text in red color:

The Mandatory Fields output

Valid Email Address

In the section for the email, just type any text which is not a valid email address. You will observe the following:

Valid Email Address Output

You have been notified that the email address which you have provided is an invalid one. This means that a valid email address has to be provided. With the directive “ng-model,” the input is bound to the model. We have two properties for the model object, that is, the user and the email.