Google+

Monday, May 11, 2015

#9 - HTML5 Forms, Data Validation and Error Messages in AngularJS

In this article we review how to use  HTML5 Forms, Data Validation and Error Messages in AngularJS,  by developing an Angular App that includes a View with a web form where to enter data, which will be validated throwing error messages    .
This is the Lesson #9 in the "AngularJS: From 0 To 100"   articles written for  Beginners. This lessons start at Lesson #1   .
<<<< PREVIOUS LESSON                              NEXT LESSON >>>>


Here we're using the  "Brackets"  free web Editor , which support for AngularJS Apps : see more in this post.

Our AngularJS App will be shown this way :
HTML5 Forms, Data Validation and Error Messages in AngularJS




HTML5 Forms, Data Validation and Error Messages in AngularJS



First of all, we declare an Angular App by referencing the AngularJS framework  :

HTML5 Forms, Data Validation and Error Messages in AngularJS        1

(copy-paste):

<!doctype html>
<html data-ng-app="MusicApp">
<head>
<title>
    AngularJS Forms Validation
</title>
     
<link href="Controllers.css" rel="stylesheet" type="text/css"  />
<script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<script src="Controllers.js" type="text/javascript"></script>

</head>



Then we add the  AngularJS View from the previous Lesson #8 :

HTML5 Forms, Data Validation and Error Messages in AngularJS     2

(copy-paste):

<div class="centered"> 
        <h1>Fragile State Discography</h1>     
        <h2>Neil Cowley (Zero 7) and Ben Mynott</h2>  
    </div>
    <div id="controls1" data-ng-controller="MusicController">    
        <ul >                
            <li data-ng-repeat="album in albums">                        
                .{{$index + 1}}            
                <img src="{{album.img}}" alt="{{album.name}}"  >             
                <span >{{album.name}} - {{album.price | currency:"USD$" | uppercase}}</span>                    </li>             
        </ul><br />        
</div>   
</body>
</html>

In the javascript file, add the Controller as follows:

HTML5 Forms, Data Validation and Error Messages in AngularJS           3

We just populated the albums list. Browse to check if its OK:

HTML5 Forms, Data Validation and Error Messages in AngularJS        4

Next, append the HTML5 form as follows:

HTML5 Forms, Data Validation and Error Messages in AngularJS          5

Now add the Controller method as follows:

HTML5 Forms, Data Validation and Error Messages in AngularJS         6
You can see that the method "submitForm()"  fakes the sending of the data by outputting the "Order" object to the Console.

(copy-paste):

var oMusicApp = angular.module('MusicApp', []);

oMusicApp.controller('MusicController', [ '$scope', function ($scope) {
           
            var albums = 
            [
                {id:111,img:"Nocturnal.jpg",name:"Nocturnal Beats",price:"12.50"},
                {id:112,img:"Facts.jpg",name:"The Facts And The Dreams",price:"11.20"},
                {id:113,img:"Voices.jpg",name:"Voices From The Dust Bowl",price:"13.70"},
                {id:114,img:"Pretz.jpg",name:"Soundcastles",price:"14.80"}
            ]
            $scope.albums = albums;
                                 
             
            $scope.submitForm = function() {
                console.log('Your Purchase Order : ', $scope.order);
                  
            };
}]);
                               
           


Next, we append an HTML5 form with two input elements, and using the AngularJS data-ng-submit directive for calling the Controller's "submitForm()" method on form submit:

HTML5 Forms, Data Validation and Error Messages in AngularJS         7

(copy-paste):

<form data-ng-submit="submitForm()" name="PurchaseForm">
                
            Your email <br />
            <input type="email" name="userEmail" data-ng-model="order.Email" > <br />
              
            Item's quantity<br />
            <input type="number" name="quantity" min="1" data-ng-model="order.Quantity"  >
              <br />     

            <input type="submit" value="Send" >
                
  </form>


Browse to your App to check whether everything's fine:

HTML5 Forms, Data Validation and Error Messages in AngularJS

Now we need to add a "select" element, bound to the "ID" property of an inner "album" object in the "Order" (that's why the data-ng-model will be "order.album.id" ):

HTML5 Forms, Data Validation and Error Messages in AngularJS          8

The data-ng-options directive tells to the AngularJS engine to add an "option" element for each "album in albums", and to set as value the "album.id" property, and as text , the "album.name + album.price" properties chained.

(copy-paste):

         Selected Album<br />
            <select   data-ng-model="order.album.id"  
            data-ng-options="album.id as album.name +'($'+album.price+')' for album in albums
            required>
            </select><br />


Browse and refresh the app:

HTML5 Forms, Data Validation and Error Messages in AngularJS

HTML5 Forms, Data Validation and Error Messages in AngularJS          9


Open the Developers Tools ( F12 ) and see the Console:

HTML5 Forms, Data Validation and Error Messages in AngularJS        10

You can see the "Order" object and its properties, including the "album" object.
But, what if the user clicks the Submit button with no data at all?:

HTML5 Forms, Data Validation and Error Messages in AngularJS        11

In this case, the "Order" object will be undefined.
Therefore, let's add Data Validation to our form:

HTML5 Forms, Data Validation and Error Messages in AngularJS       12

We just tell Angular to disable the "Submit" button if the form is "$invalid", that in our case means that at least one of the three input elements is empty, or that the Email length is shorter than 8.

(copy-paste):

<form data-ng-submit="submitForm()" name="PurchaseForm">
                
            Your email <br />
            <input type="email" name="userEmail" data-ng-model="order.Email" 
                   required data-ng-minlength="8" >
            <br />
              
            Item's quantity<br />
            <input type="number" name="quantity" min="1" data-ng-model="order.Quantity"  required>
             <br />
              
            Selected Album<br />
            <select   data-ng-model="order.album.id"  
            data-ng-options="album.id as album.name +'($'+album.price+')' for album in albums" 
            required>
            </select><br />

            <input type="submit" value="Send" data-ng-disabled="PurchaseForm.$invalid">
                
    </form>

Refresh the web page, and test it:

HTML5 Forms, Data Validation and Error Messages in AngularJS           13

If the album has not been selected, then the "submit" button will be disabled.
Select an album:

HTML5 Forms, Data Validation and Error Messages in AngularJS           14

It works fine, but the User has no clue why the button is not enabled. We must add Error messages to the web form, as follows:

HTML5 Forms, Data Validation and Error Messages in AngularJS        15

We declare here, that if the Email is invalid, or shorter than 8, or has not been provided, then the corresponding Errors should be shown . Same thing for the Quantity.

(copy-paste):

<form data-ng-submit="submitForm()" name="PurchaseForm">
                
            Your email <br />
            <input type="email" name="userEmail" data-ng-model="order.Email" 
                   required data-ng-minlength="8" >
            <span data-ng-show="PurchaseForm.userEmail.$error.required" class="errorMessage">
                *
            </span>
            <span data-ng-show="PurchaseForm.userEmail.$invalid" class="errorMessage">
                Please type a valid Email
            </span>
            <span data-ng-show="PurchaseForm.userEmail.$error.minlength" class="errorMessage">
                (Minimum length 8)
            </span><br />
              
            Item's quantity<br />
            <input type="number" name="quantity" min="1" data-ng-model="order.Quantity"  required>
             <span data-ng-show="PurchaseForm.quantity.$error.required" class="errorMessage">
                *    Please select a value&nbsp;&nbsp;&nbsp;&nbsp;
            </span> <br />
              
            Selected Album<br />
            <select   data-ng-model="order.album.id"  
            data-ng-options="album.id as album.name +'($'+album.price+')' for album in albums" 
            required>
            </select><br />

            <input type="submit" value="Send" data-ng-disabled="PurchaseForm.$invalid">
                
   </form>

Refresh the web page:

HTML5 Forms, Data Validation and Error Messages in AngularJS        16

Now the User can know why the input is illegal. If we type a valid email, the error message will be gone:

HTML5 Forms, Data Validation and Error Messages in AngularJS       17

Entering all required fields will therefore enable the Submit button:

HTML5 Forms, Data Validation and Error Messages in AngularJS     18



That's All!!! You have begun using HTML5 Forms, Data Validation and Error Messages in AngularJS  . In the next article we will continue to learn Step by Step how to use AngularJS $services with Dependency Injection by example 
If you liked the CSS3 style, here you have the code to copy:

 div[id^=controls]{padding:5px 5px 5px 25px;margin:10px 15px 15px 25px;font:900 12px Comic Sans MS;opacity:0.9;background:#fed;    border:10px solid #ddd;    border-radius: 10px;box-shadow:10px 10px 2px #c0c0c0;}button,input[type=submit] {padding:5px 5px 5px 5px;margin:10px 15px 15px 15px;width:220px;text-align: center;background:#ddd; font:900 14px Comic Sans MS;opacity:0.9;border:1px solid #c0c0c0;    border-radius: 10px;box-shadow:10px 10px 2px #c0c0c0;}ul{list-style:none;    }input {padding:5px 5px 5px 5px;margin:10px 15px 15px 15px;width:150px;text-align: center;background:#fea; font:900 12px Comic Sans MS;opacity:0.9;border:7px solid #ddd;    border-radius: 10px;box-shadow:10px 10px 2px #c0c0c0;}select{padding:5px 5px 5px 5px;margin:10px 15px 15px 15px;width:250px;text-align: center;background:#fea; font:900 12px Comic Sans MS;opacity:0.9;border:1px solid #fe9;    border-radius: 10px;box-shadow:10px 10px 2px #c0c0c0;}div.centered{ text-align:center   }.errorMessage{ color:red;   }}




<<<< PREVIOUS LESSON                              NEXT LESSON >>>>

Enjoy AngularJS.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן



No comments:

Post a Comment