Click here to Skip to main content
15,884,537 members
Articles / Web Development / HTML

AngularJS Validation

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
18 May 2015CPOL2 min read 23.8K   369   9   3
Let's try to use validation in AngularJS using ng-message.

I have put a live preview available here:

Also, if you don't want to download source from CodeProject, you can go to my github page:

Introduction

Previously, I wrote a tip about validation in AngularJS. You can find the article here:

But one of the comments wanted a version using AngularJS ng-message directive. I will use my original version application but rewrite it to use ng-message instead of ng-show. For this to work, we have to include an AngularJS module called angular-messages.js. You can view the descript and download the source code here:

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 browsers. AngularJS comes with validation built in so now it's much easier to create validation that works across browsers.

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

Image 1

Using the Code

Using angular-message

To use angular-message, you have to inject into your app module like this:
HTML
angular.module("realestateApp", ["ngMessages"]);

Now ng-message will be available to you to use.

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, Maximum, 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 />

Maximum Length

This attribute allows a maximum 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

Previously, we are using error-container, but now we can just use ng-message directive:

HTML
<div ng-messages="tenantForm.Email.$error" 
ng-messages-include="messages.html" class="errors"></div>

We also need a messages.html file to store your error messages:

HTML
<div class="messages">
    <div ng-message="required">Required</div>
    <div ng-message="minlength">Too short</div>
    <div ng-message="maxlength">Too long</div>
    <div ng-message="email">Invalid email address</div>
    <div ng-message="compareTo">Must match the previous entry</div>
    <div ng-message="number">Must be a number</div>
    <div ng-message="url">Must be in URL format</div>
</div>

Error Messages Override

Sometimes, you need to have custom error messages not covered in messages.html. You can do this by adding a special span tag for any custom error message you want to display:

HTML
  <div ng-messages="tenantForm.FirstName.$error" 
ng-messages-include="messages.html" class="errors">
     <span class="messages" 
     ng-message="minlength">Must be more than 3 characters</span> 
     <span class="messages" 
     ng-message="maxlength">Must be more than 20 characters</span> 
  </div>

Putting It All Together

Now we can combine messages.html with index.html.

HTML
 <form name="tenantForm" novalidate style="width: 500px">
    <div class="row">
        <div ng-repeat="tenant in tenant">
            <div class="form-group">
                <label>First Name: </label>
                <input type="text"
                       placeholder="First Name"
                       name="FirstName"
                       ng-model="tenant.FirstName"
                       ng-minlength=3
                       ng-maxlength=20 required />
                <div ng-messages="tenantForm.FirstName.$error" 
                     ng-messages-include="messages.html" class="errors">
                    <span class="messages" 
                    ng-message="minlength">Must be more than 3 characters</span> 
                    <span class="messages" 
                    ng-message="maxlength">Must be more than 20 characters</span> 
                </div>
            </div>
            <div class="form-group">
                <label>Home Phone: </label>
                <input type="number"
                       placeholder="Phone Number"
                       name="HomePhone"
                       ng-model="tenant.HomePhone"
                       ng-minlength=7
                       ng-maxlength=10 required />
                <div ng-messages="tenantForm.HomePhone.$error" 
                     ng-messages-include="messages.html" class="errors">
                    <span class="messages" 
                    ng-message="minlength">Must be more than 7 digits</span>
                    <span class="messages" 
                    ng-message="maxlength">Must be less than 11 digits</span>  
                </div>
            </div>
            <div class="form-group">
                <label>Email: </label>
                <input type="email"
                       placeholder="Email"
                       name="Email"
                       ng-model="tenant.Email"
                       required />
                <div ng-messages="tenantForm.Email.$error" 
                     ng-messages-include="messages.html" class="errors"></div>

            </div>
            <div class="form-group">
                <label>Webpage: </label>
                <input type="url"
                       placeholder="Webpage"
                       name="Webpage"
                       ng-model="tenant.Webpage"
                       required />
                <div ng-messages="tenantForm.Webpage.$error" 
                     ng-messages-include="messages.html" class="errors">
                </div>
            </div>
        </div>
    </div>               
</form>

 

HTML
<div class="messages">
    <div ng-message="required">Required</div>
    <div ng-message="minlength">Too short</div>
    <div ng-message="maxlength">Too long</div>
    <div ng-message="email">Invalid email address</div>
    <div ng-message="compareTo">Must match the previous entry</div>
    <div ng-message="number">Must be a number</div>
    <div ng-message="url">Must be in URL format</div>
</div>

This approach feels cleaner than using ng-show directive. Also, it reduces code duplication by having a central place to store your error messages but at the same time allows for custom messages.

In my next article, I will talk about having a central location to store validation logic for ease of maintenance. Also, I would like to add internationalization for error messages in multiple languages.

Thanks for reading.

History

  • Version 1 5/18/2015 Created first draft

License

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


Written By
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

 
PraiseWell Explained..! Pin
Member 1392909628-Jul-18 2:54
Member 1392909628-Jul-18 2:54 
QuestionGreat Pin
stibee30-Jul-15 23:21
stibee30-Jul-15 23:21 
QuestionComments are welcome. Pin
Tony Jen19-May-15 0:36
Tony Jen19-May-15 0:36 

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.