Hello Readers,
Hope you are doing good today.
Today on My blog, I am going to explain how you use Form Validation in AngularJS. First, you need to use the AngularJS library in your page. AngularJS provides client-side form validation. Validation notifies the user about the current state of fields.
First Create an index.html page and put required library file in <head></head> section:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
Then Add below code in your index.html page.
In form we are using novalidate attribute which disable default browser validation
ng-model directive binds the input elements to the model.here we are using username & email properties.
ng-show display the current state of fields.
<form ng-app="myApp" ng-controller="myCntrl" name="myForm" novalidate>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Please Enter UserName.</span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Please Enter e-Mail.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
For validation write below script :
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCntrl', function($scope) {
$scope.user = 'rafi';
$scope.email = 'rafi@yahoo.com';
});
</script>
I hope this will help you. Please feel free to give us your feedback in comments.
0 Comment(s)