Click here to Skip to main content
15,394,327 members
Articles / Web Development / HTML
Tip/Trick
Posted 17 May 2015

Stats

45.5K views
915 downloads
19 bookmarked

Validation in AngularJS

Rate me:
Please Sign up or sign in to vote.
4.96/5 (12 votes)
17 May 2015CPOL2 min read
Here, we will add validation logic to our AngularJS app.

Update: I have a new article on the new features of AngularJS validation using ng-message. Check it out here:

http://www.codeproject.com/Articles/992545/AngularJS-Validation

Introduction

I previously wrote about creating a simple CRUD application using AngularJS. The link is here: An Overview of an AngularJS Project. Now, I would like to add a validation layer to make sure data entered is valid. For this tip, I will only use some of my data for validation.

I'm going to use Visual Studio 2013 community version with some dependencies like AngularJS, Bootstrap and Jquery.

I have a live preview for you to look at, please click on this link to view:

http://tonyjen.github.io/AngularJSValidation/

Background

Validation was always difficult in a web application. Many times, frameworks need to be used for validating form values. Also, these frameworks often don't work across all browers. AngularJS comes with validation built in so now it's much easier to create validation that works across browers.

Here is a screen shot of what the validation feature is supposed to look like:

Image 1

Using the Code

Form

To initialize the validation process, you should start with a form container like this:

HTML
<form name="tenantForm"> 

Now inside the form, you can take input controls and add validation logic to them.

In validation scenarios, we typically have a few main attributes we would like to validate. They are Required, Minimum, Maxium, Pattern, Email, Number, and URL.

Required

This attribute forces the form to be invalid if a required field is not entered.

HTML
<input type="text" required />

Minimum Length

This attribute requires a minimum of characters before input can be accepted.

HTML
<input type="text" ng-minlength=5 />

Maxium Length

This attribute allows a maxium length of character or validation will fail.

HTML
<input type="text" ng-maxlength=20 />

Pattern Matching

This feature allows for custom matching using Regex.

HTML
<input type="text" ng-pattern="[a-zA-Z]" />

Email Matching

Angular provides a custom email matching feature.

HTML
<input type="email" name="email" ng-model="user.email" />

Number

This requires input to be numeric format before validation.

HTML
<input type="number" name="age" ng-model="user.age" />

URL

This requires input to be in a link format before validation.

HTML
<input type="url" name="homepage" ng-model="user.url" />

Error Messages

After creating the input controls, we now need a place to display errors when validation fails. We first start with a container with error-container. Then, we will go through each error type and display the correct error text:

HTML
<div class="error-container"
   ng-show="tenantForm.FirstName.$dirty && tenantForm.FirstName.$invalid">
   <small class="text-danger"
      ng-show="tenantForm.FirstName.$error.required">
      Your name is required.
   </small>
   <small class="text-danger"
      ng-show="tenantForm.FirstName.$error.minlength">
      Your name is required to be at least 3 characters
   </small>
   <small class="text-danger"
      ng-show="tenantForm.FirstName.$error.maxlength">
      Your name cannot be longer than 20 characters
   </small>
</div>

After adding form control with data properties and error message classes, the application will perform a validation in each input control and display any validation errors.

Putting It All Together

So after combining the input and validation parts of the form, the HTML would look like this:

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Real Estate</title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="realEstateApp/site.css" rel="stylesheet" />
</head>
<body ng-app="realestateApp" class="ng-scope">
    <div class="panel panel-default">
      
        <div class="container" ng-controller="tenantsController" ngcloak>
            <h1>Tenants</h1>
            <div class="row">
                <div>
                    <button class="btn btn-primary" ng-click="previousTenant()">
                        Previous
                    </button>
                    <button class="btn btn-primary" ng-click="nextTenant()">
                        Next
                    </button>
                    <button class="btn btn-success" ng-click="addTenant()">
                        Add
                    </button>
                    <button class="btn btn-danger" ng-click="deleteTenant()">
                        Delete
                    </button>
                    <br style="clear:both">
                    <br>
                </div>
            </div>
            <form name="tenantForm" style="width: 500px">
                <div class="row">
                    <div ng-repeat="tenant in tenant">
                        <div>
                            <label>First Name: </label>
                            <input type="text"
                                   placeholder="First Name"
                                   name="FirstName"
                                   ng-model="tenant.FirstName"
                                   ng-minlength=3
                                   ng-maxlength=20 required />
                        </div>
                        <div class="error-container"
                             ng-show="tenantForm.FirstName.$dirty && tenantForm.FirstName.$invalid">
                            <small class="text-danger"
                                   ng-show="tenantForm.FirstName.$error.required">
                                Your name is required.
                            </small>
                            <small class="text-danger"
                                   ng-show="tenantForm.FirstName.$error.minlength">
                                Your name is required to be at least 3 characters
                            </small>
                            <small class="text-danger"
                                   ng-show="tenantForm.FirstName.$error.maxlength">
                                Your name cannot be longer than 20 characters
                            </small>
                        </div>
                        <div>
                            <label>Home Phone:</label>
                            <input type="number"
                                   placeholder="Home Phone"
                                   name="HomePhone"
                                   ng-model="tenant.HomePhone"
                                   ng-minlength=7
                                   ng-maxlength=10 required />
                        </div>
                            <div class="error-container"
                                 ng-show="tenantForm.HomePhone.$dirty && tenantForm.HomePhone.$invalid">
                                <small class="text-danger"
                                       ng-show="tenantForm.HomePhone.$error.required">
                                    Your home phone is required.
                                </small>
                                <small class="text-danger"
                                       ng-show="tenantForm.HomePhone.$error.minlength">
                                    Your home phone is required to be at least 7 digits
                                </small>
                                <small class="text-danger"
                                       ng-show="tenantForm.HomePhone.$error.maxlength">
                                    Your home phone cannot be longer than 10 digits
                                </small>
                                <small class="text-danger"
                                       ng-show="tenantForm.HomePhone.$error.number">
                                    Your home phone cannot be characters
                                </small>
                            </div>
                            <div>
                                <label>Email:</label>
                                <input type="email"
                                       placeholder="Email"
                                       name="Email"
                                       ng-model="tenant.Email"
                                       required />
                            </div>
                            <div class="error-container"
                                 ng-show="tenantForm.Email.$dirty && tenantForm.Email.$invalid">
                                <small class="text-danger"
                                       ng-show="tenantForm.Email.$error.required">
                                    Your email is required.
                                </small>
                                <small class="text-danger"
                                       ng-show="tenantForm.Email.$error.email">
                                    Your email is not valid
                                </small>
                            </div>
                            <div>
                                <label>Webpage:</label>
                                <input class="input-large"
                                       type="url"
                                       placeholder="Webpage"
                                       name="Webpage"
                                       ng-model="tenant.Webpage"
                                       required />
                            </div>
                            <div class="error-container"
                                 ng-show="tenantForm.Webpage.$dirty && tenantForm.Webpage.$invalid">
                                <small class="text-danger"
                                       ng-show="tenantForm.Webpage.$error.required">
                                    Your webpage is required.
                                </small>
                                <small class="text-danger"
                                       ng-show="tenantForm.Webpage.$error.url">
                                    Your webpage is not valid
                                </small>
                            </div>
                        </div>
                    </div>
            </form>
        </div>
    </div>

    <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/angular.js"></script>
    <script src="realEstateApp/realestateApp.js"></script>
    <script src="realEstateApp/controllers/tenantsController.js"></script>
    <script src="realEstateApp/services/tenantService.js"></script>
</body>
</html>

Validation using AngularJS is much simpler and more concise than using 3rd party jquery libraries. Now your application can have validation without a lot of pain involved. I have provided a sample of my application which validates some common attributes, you can extend it or try to create your own.

History

  • Version 1 5/16/205

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tony Jen
United States United States
Hello, I'm a developer in the Orlando area. I enjoy playing basketball, golf and learning about new technologies. I have a passion in the web development space and hope to learn more about how to creating useful apps and more importantly share my knowledge with the community.

I'm available for freelance work, specializing in web applications.
You can reach me at tonyjen0905@gmail.com

Comments and Discussions

 
QuestionHow to stop spam enquries in a website Pin
Member 1507424616-Feb-21 6:13
MemberMember 1507424616-Feb-21 6:13 
QuestionThank you for sharing Pin
johnabrahamuniv3-Aug-20 5:20
Memberjohnabrahamuniv3-Aug-20 5:20 
QuestionDo you guys support for aws projects too ? Pin
Mithun “Mithun” R27-Jul-20 21:59
MemberMithun “Mithun” R27-Jul-20 21:59 
QuestionInformative Post. Pin
SAP Academy19-Jul-20 3:59
MemberSAP Academy19-Jul-20 3:59 
AnswerMessage Closed Pin
19-Jul-20 3:56
MemberSAP Academy19-Jul-20 3:56 
QuestionAngular2 Pin
Member 1399947526-Sep-18 23:49
MemberMember 1399947526-Sep-18 23:49 
GeneralAwesome Post on Angular JS validation Pin
Member 1170427019-May-15 19:41
MemberMember 1170427019-May-15 19:41 
GeneralRe: Awesome Post on Angular JS validation Pin
Tony Jen19-May-15 23:03
MemberTony Jen19-May-15 23:03 
GeneralRe: Awesome Post on Angular JS validation Pin
Tony Jen19-May-15 23:05
MemberTony Jen19-May-15 23:05 
QuestionHTML5 pattern attribute versus ng-pattern Pin
Gerd Wagner18-May-15 2:25
professionalGerd Wagner18-May-15 2:25 
AnswerRe: HTML5 pattern attribute versus ng-pattern Pin
Tony Jen18-May-15 9:52
MemberTony Jen18-May-15 9:52 
GeneralRe: HTML5 pattern attribute versus ng-pattern Pin
Gerd Wagner18-May-15 10:11
professionalGerd Wagner18-May-15 10:11 
GeneralRe: HTML5 pattern attribute versus ng-pattern Pin
Tony Jen18-May-15 10:37
MemberTony Jen18-May-15 10:37 
GeneralRe: HTML5 pattern attribute versus ng-pattern Pin
Gerd Wagner18-May-15 11:01
professionalGerd Wagner18-May-15 11:01 
GeneralRe: HTML5 pattern attribute versus ng-pattern Pin
Tony Jen18-May-15 11:27
MemberTony Jen18-May-15 11:27 
GeneralMy vote of 5 Pin
D V L17-May-15 19:46
professionalD V L17-May-15 19:46 
GeneralMy vote of 4 Pin
hoangcute9x17-May-15 16:39
professionalhoangcute9x17-May-15 16:39 
GeneralRe: My vote of 4 Pin
Tony Jen18-May-15 2:21
MemberTony Jen18-May-15 2:21 
QuestionComments are welcome. Pin
Tony Jen17-May-15 8:46
MemberTony Jen17-May-15 8:46 
NewsRe: Comments are welcome. Pin
Member 1507424616-Feb-21 6:09
MemberMember 1507424616-Feb-21 6:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.