SlideShare a Scribd company logo
AngularJS Form Validation
Requirements
 Name isrequired
 Username isnot required,minimumlength3,maximumlength8
 Email isnot required,buthasto be a valid email
 Form submitisdisabledif the formisn’tvalid
 Showa requiredorinvalidemail error
 Alertawesome if submittedcorrectly
Now that we know what we want, let’s get to building.
# Angular Form Properties $valid, $invalid, $pristine, $dirty
Angular provides properties on forms that help us validate them. They give us various
information about a form or its inputs and are applied to a form and inputs.
Property Class Description
$valid ng-valid Boolean Tellswhetheranitemiscurrentlyvalidbasedonthe rulesyouplaced.
$invalid ng-invalid Boolean Tellswhetheranitemiscurrentlyinvalidbasedonthe rulesyouplaced.
$pristine ng-pristine Boolean True if the form/input hasnot beenusedyet.
$dirty ng-dirty Boolean True if the form/input hasbeenused.
$touched ng-touched Boolean True if the input has beenblurred.
Angular also provides classes on the form and its inputs so that you can style each state
accordingly.
AccessingAngularFormProperties
 To access the form: <form name>.<angular property>
 To access an input: <form name>.<input name>.<angular property>
Setting Up Our Form
We will use a simple form to demonstrate.
We will need 2 files: * index.html Our code to display the form * app.js Our Angular
application and controller (barely any code at all)
Our FormCodeindex.html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS ===================== -->
<!-- load bootstrap -->
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min
.css">
<style>
body { padding-top:30px; }
</style>
<!-- JS ===================== -->
<!-- load angular -->
<script src="http://code.angularjs.org/1.2.6/angular.js"></script>
<script src="app.js"></script>
</head>
<!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header"><h1>AngularJS Form Validation</h1></div>
<!-- FORM -->
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)"
novalidate> <!-- novalidate prevents HTML5 validation since we will be
validating ourselves -->
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-
model="name" required>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control"
ng-model="user.username" ng-minlength="3" ng-maxlength="8">
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-
model="email">
</div>
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div><!-- col-sm-8 -->
</div><!-- /container -->
</body>
</html>
A few key points to note here:
 novalidate:Thiswill preventthe defaultHTML5 validationssince we’ll be doingthatourselves
(ourswill be muchprettier)
 We have applied ng-model toour inputsso that we have data fromour formsboundto
Angularvariables
 ng-minlength and ng-maxlength onusername will create those rules
 The name inputis required
 The email inputistype=”email”
ValidationRules
Angular provides many validation rules that we can use in addition to ng-minlength and ng-
maxlength.
These are the available parameters for an Angular input to create validation rules. Read the
Angular input directive for more information.
<input
ng-model="{ string }"
name="{ string }"
required
ng-required="{ boolean }"
ng-minlength="{ number }"
ng-maxlength="{ number }"
ng-pattern="{ string }"
ng-change="{ string }">
</input>
Now that we have our simple form, let’s create our Angular app and controller that we have
already applied to it using ng-app and ng-controller.
Our AngularAppCode app.js
// app.js
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
// function to submit the form after all validation has
occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
}
};
});
Disabling HTML5 Validation novalidate
We will use novalidate on our form. This is a good practice since we will handle the validation
ourselves. If we let our form do it, it will look pretty ugly.
Disabling the Submit Button ng-disabled
Now the real fun begins. We get to start using Angular properties. First let’s disable our
submit button. We only want it disabled if our form is $invalid.
<!-- index.html -->
...
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary" ng-
disabled="userForm.$invalid">Submit</button>
...
With just that little code (ng-disabled), our form button will be disabled if the form is
$invalid. This means that our name input field is required and our email input field requires a
valid email.
Showing an Error Message ng-show
ng-valid and ng-invalid will automatically determine if an input is good based on the rules
placed on it in your form.
Let’s go through and add an error message for each of our inputs if they are not $valid and have
already been used (since we don’t want to show an error before they’ve been used).
<!-- index.html -->
...
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-
model="name" required>
<p ng-show="userForm.name.$invalid &&
!userForm.name.$pristine" class="help-block">You name is
required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-
model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-
block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-
block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-
model="email">
<p ng-show="userForm.email.$invalid &&
!userForm.email.$pristine" class="help-block">Enter a valid
email.</p>
</div>
...
Just like that, Angular will automatically determine if we should show an error based on an
inputs $invalid and $pristine properties.
Styling Classes
Angular already provides classes on our inputs and our forms based on if they are valid or not.
Look at the table at the beginning of this article for those classes (ng-valid, ng-invalid, ng-
pristine and ng-dirty).
You can style those in CSS if you like. You can do anything you like with those classes. There
will even be classes based on the certain rules applied if you wanted to get really specific.
.ng-valid { }
.ng-invalid { }
.ng-pristine { }
.ng-dirty { }
.ng-touched { }
/* really specific css rules applied by angular */
.ng-invalid-required { }
.ng-invalid-minlength { }
.ng-valid-max-length { }
Adding Conditional Classes ng-class
Since we are using Bootstrap, we will use the classes they provide (has-error). This will get us
that nice error and color around our form-group.
ng-class allows us to add classes based on an expression. In this case, we want to add a has-
error class to our form-group if an input is $invalid and not pristine.
The way it works is ng-class="{ <class-you-want> : <expression to be evaluated >
}". For more information, read the Angular ngClass docs.
<!-- index.html -->
...
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' :
userForm.name.$invalid && !userForm.name.$pristine }">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-
model="user.name" required>
<p ng-show="userForm.name.$invalid &&
!userForm.name.$pristine" class="help-block">You name is
required.</p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' :
userForm.username.$invalid && !userForm.username.$pristine }">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-
model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-
block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-
block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' :
userForm.email.$invalid && !userForm.email.$pristine }">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-
model="user.email">
<p ng-show="userForm.email.$invalid &&
!userForm.email.$pristine" class="help-block">Enter a valid
email.</p>
</div>
...
Now our form has the correct Bootstrap error classes
.
Only Showing Errors After Submitting the Form
Sometimes it is not desirable to show errors while a user is typing. The errors currently show
immediately as a user is typing into the form. This happens because of Angular’s great data-
binding feature. Since everything changes immediately, it can be a downside when talking about
form validation.
For the scenario where you only want to show errors after a form is submitted, you would
adjust the above code a little bit.
1. You wouldneedtotake awaythe ng-disabled on the submitbuttonsince we wanta userto
be able to submita formevenif itis notfullyvalid.
2. You wouldadda variable afterthe formhas beensubmitted.Inside of your submitForm()
function,justadd $scope.submitted = true;. Thisstoresthe submittedvariable astrue as
soonas the formissubmitted.
3. Adjustthe errorrulesfrom ng-class="&#123; 'has-error' :
userForm.name.$invalid && !userForm.name.$pristine }" to ng-class="&#123;
'has-error' : userForm.name.$invalid && !userForm.name.$pristine &&
submitted }". Thisensuresthatthe error will onlyshow afterthe formissubmitted.You
wouldneedtoadjustall the otherng-class and ng-show to account for thisvariable.
Now the form only shows errors if the submitted variable is set to true.
# Only Showing Errors After Clicking Out of an Input
Only showing errors after clicking out of an input (also known as blur) is a little more
complicated than validating on submit. Validating a form on blur requires a custom directive. A
directive will allow you to manipulate the DOM.
We have updated this article to add the new ng-touched feature in Angular 1.3. This helps us
handle blurred inputs!
# All Done
Now once we fill out all our information correctly, our form submit button will be active. Once
we submit our form, we’ll see the alert message we set up.
With just a few simple lines we now have:
 InputValidation
 Form Errors
 CustomClasses
 Automaticallydisabledandenabledform
 CustomRules
As you can see, it is easy to use the built in Angular form validation techniques to create a client-
side validated form.
# The Future
As it stands, it is not a simple process to do validation after a user clicks out of an input. The
Angular team is aware of this and they have said they plan to add more states to handle things
like form.submitted, input.$visited, input.$blurred, or input.$touched. Here are some
resources for the future of form validation:
 GithubIssue
 ngFormModule Ideas
Hopefully sooner rather than later it’ll be easier to do validation and account for different states
of our application.
Edit #1: Addedinformationaboutvalidatingafterformsubmitoronblur.Alsoaddedresources. Edit#2:
Changedthe processformfunctiontotake the validparameter.Helpstocreate testable controllers.
Thanksto FredrikBostrom for the tip.
This article ispart of the AngularJSForms series.
 SubmittingAJAXForms:The AngularJSWay
 AngularJSFormValidation(thisarticle)
 HandlingCheckboxesandRadioButtonsinAngularForms

More Related Content

DOCX
Angular js form validation with ngmessages shashi-19-7-16
PPTX
Form Validation in JavaScript
PDF
Styling recipes for Angular components
PPTX
Emberjs as a rails_developer
KEY
Building Web Service Clients with ActiveModel
PPTX
Angular Mini-Challenges
PPT
Form demoinplaywithmysql
PDF
One App Cloud - Custom CSS and Javascript
Angular js form validation with ngmessages shashi-19-7-16
Form Validation in JavaScript
Styling recipes for Angular components
Emberjs as a rails_developer
Building Web Service Clients with ActiveModel
Angular Mini-Challenges
Form demoinplaywithmysql
One App Cloud - Custom CSS and Javascript

What's hot (20)

KEY
Building Web Service Clients with ActiveModel
PPTX
Android Training (Android UI)
PDF
Introduction To Angular's reactive forms
DOCX
Filters in AngularJS
PDF
Unbreakable Domain Models PHPUK 2014 London
PPTX
Data validation in web applications
PDF
Write Tests in End Users’ Lingo
PPTX
Cape Town MS Developer User Group: Xamarin Community Toolkit
PPTX
Introduction to Javascript
DOCX
Built in filters
PDF
Beginner’s tutorial (part 1) integrate redux form in react native application
PDF
Basic Android Layout
PDF
HTML::FormFu talk for Sydney PM
PPTX
Continuous Quality
PDF
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
PDF
Appcelerator Titanium Kinetic practices part 1
PDF
AngularJS Basic Training
PDF
What's New in newforms-admin
PPTX
Android Layout
KEY
Sending Email with Rails
Building Web Service Clients with ActiveModel
Android Training (Android UI)
Introduction To Angular's reactive forms
Filters in AngularJS
Unbreakable Domain Models PHPUK 2014 London
Data validation in web applications
Write Tests in End Users’ Lingo
Cape Town MS Developer User Group: Xamarin Community Toolkit
Introduction to Javascript
Built in filters
Beginner’s tutorial (part 1) integrate redux form in react native application
Basic Android Layout
HTML::FormFu talk for Sydney PM
Continuous Quality
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
Appcelerator Titanium Kinetic practices part 1
AngularJS Basic Training
What's New in newforms-admin
Android Layout
Sending Email with Rails
Ad

Similar to Angular js form validation shashi-19-7-16 (20)

PPTX
Forms in AngularJS
PPTX
Angular Form Validations
PPTX
angular-np-3
PPTX
AngularJs - Part 3
PPTX
AngularJS Fundamentals: Date Entry Forms
PPTX
Form validation and animation
PPTX
Single page application 06
PDF
Master AngularJS
PPT
introduction to Angularjs basics
PDF
JavaScript - Chapter 14 - Form Handling
KEY
HTML5 Form Validation
PPTX
Angular 6 Form Validation with Material
PPTX
Form using html and java script validation
PDF
User Forms & API integration
ODP
Knolx j query-form-validation-slides
PPTX
Javascript validating form
KEY
Building & Breaking Web Forms with Quaid-JS
PDF
A Sensational Exposé With Bewildering Demonstrations
PPTX
Web topic 22 validation on web forms
PDF
Getting Started with Angular - Stormpath Webinar, January 2017
Forms in AngularJS
Angular Form Validations
angular-np-3
AngularJs - Part 3
AngularJS Fundamentals: Date Entry Forms
Form validation and animation
Single page application 06
Master AngularJS
introduction to Angularjs basics
JavaScript - Chapter 14 - Form Handling
HTML5 Form Validation
Angular 6 Form Validation with Material
Form using html and java script validation
User Forms & API integration
Knolx j query-form-validation-slides
Javascript validating form
Building & Breaking Web Forms with Quaid-JS
A Sensational Exposé With Bewildering Demonstrations
Web topic 22 validation on web forms
Getting Started with Angular - Stormpath Webinar, January 2017
Ad

Recently uploaded (20)

PPTX
Introduction and Scope of Bichemistry.pptx
PDF
Business Ethics Teaching Materials for college
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
English Language Teaching from Post-.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Pre independence Education in Inndia.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Cell Structure & Organelles in detailed.
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Introduction and Scope of Bichemistry.pptx
Business Ethics Teaching Materials for college
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
English Language Teaching from Post-.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cardiovascular Pharmacology for pharmacy students.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
NOI Hackathon - Summer Edition - GreenThumber.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O7-L3 Supply Chain Operations - ICLT Program
Anesthesia in Laparoscopic Surgery in India
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
Pre independence Education in Inndia.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Cell Structure & Organelles in detailed.
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx

Angular js form validation shashi-19-7-16

  • 1. AngularJS Form Validation Requirements  Name isrequired  Username isnot required,minimumlength3,maximumlength8  Email isnot required,buthasto be a valid email  Form submitisdisabledif the formisn’tvalid  Showa requiredorinvalidemail error  Alertawesome if submittedcorrectly Now that we know what we want, let’s get to building. # Angular Form Properties $valid, $invalid, $pristine, $dirty Angular provides properties on forms that help us validate them. They give us various information about a form or its inputs and are applied to a form and inputs.
  • 2. Property Class Description $valid ng-valid Boolean Tellswhetheranitemiscurrentlyvalidbasedonthe rulesyouplaced. $invalid ng-invalid Boolean Tellswhetheranitemiscurrentlyinvalidbasedonthe rulesyouplaced. $pristine ng-pristine Boolean True if the form/input hasnot beenusedyet. $dirty ng-dirty Boolean True if the form/input hasbeenused. $touched ng-touched Boolean True if the input has beenblurred. Angular also provides classes on the form and its inputs so that you can style each state accordingly. AccessingAngularFormProperties  To access the form: <form name>.<angular property>  To access an input: <form name>.<input name>.<angular property> Setting Up Our Form We will use a simple form to demonstrate. We will need 2 files: * index.html Our code to display the form * app.js Our Angular application and controller (barely any code at all)
  • 3. Our FormCodeindex.html <!-- index.html --> <!DOCTYPE html> <html> <head> <!-- CSS ===================== --> <!-- load bootstrap --> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min .css"> <style> body { padding-top:30px; } </style> <!-- JS ===================== --> <!-- load angular --> <script src="http://code.angularjs.org/1.2.6/angular.js"></script> <script src="app.js"></script> </head> <!-- apply angular app and controller to our body --> <body ng-app="validationApp" ng-controller="mainController"> <div class="container"> <div class="col-sm-8 col-sm-offset-2"> <!-- PAGE HEADER --> <div class="page-header"><h1>AngularJS Form Validation</h1></div> <!-- FORM --> <!-- pass in the variable if our form is valid or invalid --> <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves --> <!-- NAME --> <div class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" ng- model="name" required> </div> <!-- USERNAME --> <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8"> </div> <!-- EMAIL --> <div class="form-group"> <label>Email</label>
  • 4. <input type="email" name="email" class="form-control" ng- model="email"> </div> <!-- SUBMIT BUTTON --> <button type="submit" class="btn btn-primary">Submit</button> </form> </div><!-- col-sm-8 --> </div><!-- /container --> </body> </html> A few key points to note here:  novalidate:Thiswill preventthe defaultHTML5 validationssince we’ll be doingthatourselves (ourswill be muchprettier)  We have applied ng-model toour inputsso that we have data fromour formsboundto Angularvariables  ng-minlength and ng-maxlength onusername will create those rules  The name inputis required  The email inputistype=”email” ValidationRules Angular provides many validation rules that we can use in addition to ng-minlength and ng- maxlength. These are the available parameters for an Angular input to create validation rules. Read the Angular input directive for more information. <input ng-model="{ string }" name="{ string }" required ng-required="{ boolean }" ng-minlength="{ number }" ng-maxlength="{ number }" ng-pattern="{ string }" ng-change="{ string }"> </input> Now that we have our simple form, let’s create our Angular app and controller that we have already applied to it using ng-app and ng-controller.
  • 5. Our AngularAppCode app.js // app.js // create angular app var validationApp = angular.module('validationApp', []); // create angular controller validationApp.controller('mainController', function($scope) { // function to submit the form after all validation has occurred $scope.submitForm = function(isValid) { // check to make sure the form is completely valid if (isValid) { alert('our form is amazing'); } }; }); Disabling HTML5 Validation novalidate We will use novalidate on our form. This is a good practice since we will handle the validation ourselves. If we let our form do it, it will look pretty ugly. Disabling the Submit Button ng-disabled Now the real fun begins. We get to start using Angular properties. First let’s disable our submit button. We only want it disabled if our form is $invalid. <!-- index.html --> ... <!-- SUBMIT BUTTON -->
  • 6. <button type="submit" class="btn btn-primary" ng- disabled="userForm.$invalid">Submit</button> ... With just that little code (ng-disabled), our form button will be disabled if the form is $invalid. This means that our name input field is required and our email input field requires a valid email. Showing an Error Message ng-show ng-valid and ng-invalid will automatically determine if an input is good based on the rules placed on it in your form. Let’s go through and add an error message for each of our inputs if they are not $valid and have already been used (since we don’t want to show an error before they’ve been used). <!-- index.html --> ... <!-- NAME --> <div class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" ng- model="name" required> <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p> </div> <!-- USERNAME --> <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control" ng- model="user.username" ng-minlength="3" ng-maxlength="8"> <p ng-show="userForm.username.$error.minlength" class="help- block">Username is too short.</p> <p ng-show="userForm.username.$error.maxlength" class="help- block">Username is too long.</p> </div> <!-- EMAIL --> <div class="form-group"> <label>Email</label> <input type="email" name="email" class="form-control" ng- model="email">
  • 7. <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p> </div> ... Just like that, Angular will automatically determine if we should show an error based on an inputs $invalid and $pristine properties. Styling Classes Angular already provides classes on our inputs and our forms based on if they are valid or not. Look at the table at the beginning of this article for those classes (ng-valid, ng-invalid, ng- pristine and ng-dirty). You can style those in CSS if you like. You can do anything you like with those classes. There will even be classes based on the certain rules applied if you wanted to get really specific.
  • 8. .ng-valid { } .ng-invalid { } .ng-pristine { } .ng-dirty { } .ng-touched { } /* really specific css rules applied by angular */ .ng-invalid-required { } .ng-invalid-minlength { } .ng-valid-max-length { } Adding Conditional Classes ng-class Since we are using Bootstrap, we will use the classes they provide (has-error). This will get us that nice error and color around our form-group. ng-class allows us to add classes based on an expression. In this case, we want to add a has- error class to our form-group if an input is $invalid and not pristine. The way it works is ng-class="{ <class-you-want> : <expression to be evaluated > }". For more information, read the Angular ngClass docs. <!-- index.html --> ... <!-- NAME -->
  • 9. <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"> <label>Name</label> <input type="text" name="name" class="form-control" ng- model="user.name" required> <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p> </div> <!-- USERNAME --> <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }"> <label>Username</label> <input type="text" name="username" class="form-control" ng- model="user.username" ng-minlength="3" ng-maxlength="8"> <p ng-show="userForm.username.$error.minlength" class="help- block">Username is too short.</p> <p ng-show="userForm.username.$error.maxlength" class="help- block">Username is too long.</p> </div> <!-- EMAIL --> <div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }"> <label>Email</label> <input type="email" name="email" class="form-control" ng- model="user.email"> <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p> </div> ... Now our form has the correct Bootstrap error classes
  • 10. . Only Showing Errors After Submitting the Form Sometimes it is not desirable to show errors while a user is typing. The errors currently show immediately as a user is typing into the form. This happens because of Angular’s great data- binding feature. Since everything changes immediately, it can be a downside when talking about form validation. For the scenario where you only want to show errors after a form is submitted, you would adjust the above code a little bit. 1. You wouldneedtotake awaythe ng-disabled on the submitbuttonsince we wanta userto be able to submita formevenif itis notfullyvalid. 2. You wouldadda variable afterthe formhas beensubmitted.Inside of your submitForm() function,justadd $scope.submitted = true;. Thisstoresthe submittedvariable astrue as soonas the formissubmitted. 3. Adjustthe errorrulesfrom ng-class="&#123; 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }" to ng-class="&#123; 'has-error' : userForm.name.$invalid && !userForm.name.$pristine && submitted }". Thisensuresthatthe error will onlyshow afterthe formissubmitted.You wouldneedtoadjustall the otherng-class and ng-show to account for thisvariable. Now the form only shows errors if the submitted variable is set to true.
  • 11. # Only Showing Errors After Clicking Out of an Input Only showing errors after clicking out of an input (also known as blur) is a little more complicated than validating on submit. Validating a form on blur requires a custom directive. A directive will allow you to manipulate the DOM. We have updated this article to add the new ng-touched feature in Angular 1.3. This helps us handle blurred inputs! # All Done Now once we fill out all our information correctly, our form submit button will be active. Once we submit our form, we’ll see the alert message we set up. With just a few simple lines we now have:  InputValidation  Form Errors  CustomClasses  Automaticallydisabledandenabledform  CustomRules As you can see, it is easy to use the built in Angular form validation techniques to create a client- side validated form. # The Future As it stands, it is not a simple process to do validation after a user clicks out of an input. The Angular team is aware of this and they have said they plan to add more states to handle things like form.submitted, input.$visited, input.$blurred, or input.$touched. Here are some resources for the future of form validation:  GithubIssue  ngFormModule Ideas
  • 12. Hopefully sooner rather than later it’ll be easier to do validation and account for different states of our application. Edit #1: Addedinformationaboutvalidatingafterformsubmitoronblur.Alsoaddedresources. Edit#2: Changedthe processformfunctiontotake the validparameter.Helpstocreate testable controllers. Thanksto FredrikBostrom for the tip. This article ispart of the AngularJSForms series.  SubmittingAJAXForms:The AngularJSWay  AngularJSFormValidation(thisarticle)  HandlingCheckboxesandRadioButtonsinAngularForms