Tutorials for web designers and developers
Tutorials for Developers_
Search
Close this search box.
Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar is an expert Web Developer, SEO specialist, and Graphic Designer. Hafiz Faraz is an expert in WordPress design and development. Hire on Upwork | Hire on Fiverr

Lets see how we can add form validation in angularjs application. We will be making use of our exisiting guitar application which we have been working in  Tutorial 13: Tabs in AngularJS . You can download previous tutorial complete app here. This tutorial is somehow little bit similar to Tutorial 8: data binding tutorial that we saw earlier. So to start angularjs form validation, open the details.html page in project files. Details.html file contain details of each guitar plus some tabs. We have to work under reviews tab, where we will be adding some reviews to the guitar details using form validation.

First

update the data.json file, because I have added some new entries to guitar:

[
		{
			"name" 		 : "Acoustic Guitar",
			"description": "Acoustic, electro-acoustic and classical guitars, from leading brands in world.",
			"longDescription" : "An acoustic guitar is a guitar that uses only acoustic (as opposed to electronic) means to transmit the strings vibrational energy to the air in order to produce a sound. This typically involves the use of a sound board and a sound box to amplify the vibrations of the string. The source of sound in an acoustic guitar is the string, which is plucked with the fingers or with a plectrum. The string vibrates at a fundamental frequency but also creates many harmonics at different frequencies. The frequencies produced depend on string length, mass, and tension. The string causes the soundboard and sound box to vibrate, and as these have their own resonances at certain frequencies, they amplify some string harmonics more strongly than others, hence affecting the timbre produced by the instrument.",
			"image" : "Acoustic",
			"price" : "23.78",
			"specifications" : "Specifications of ",
			"dateAdded" : "1403926823000",
			"category" : "expensive",
			"soldOut" : "false",
			"reviews" : [{
					"star" : "5",
					"body" : "I love this guitar. I am really satisfied by the quality and definitly recommend you to buy this guitar.",
					"name" : "Hafiz"
				},
				{
					"star" : "4",
					"body" : "I like this product. It is a wonderful peace of art with beautiful cords.",
					"name" : "Faraz"
				}]
		},
		{
			"name" 		 : "Electric Guitar",
			"description": "Ever-popular solid-body guitars, to hollow-body guitars and archtops.",
			"longDescription" : "An electric guitar is a guitar that uses a pickup to convert the vibration of its strings into electrical impulses. The most common guitar pickup uses the principle of direct electromagnetic induction. The signal generated by an electric guitar is too weak to drive a loudspeaker, so it is amplified before sending it to a loudspeaker. Since the output of an electric guitar is an electric signal, the signal may easily be altered using electronic circuits to add color to the sound. Often the signal is modified using effects such as reverb and distortion.",
			"image"	:  "Electric",
			"price" : "18.34",
			"specifications" : "Specifications of ",
			"dateAdded" : "1399779623000",
			"category" : "expensive",
			"soldOut" : "false",
			"reviews" : [{
					"star" : "2",
					"body" : "I hate this guitar. I am really dissatisfied by the quality of this guitar.",
					"name" : "John"
				},
				{
					"star" : "3",
					"body" : "Its a normal guitarr. Although, it has beautiful cords.",
					"name" : "Tammy"
				}]
		},
		{
			"name" 		 : "Bass Guitar",
			"description": "Classic Fender Bass, Precision and Jazz basses, to Gibson Thunderbirds.",
			"longDescription" : "The bass guitar (also called electric bass,or simply bass) is a stringed instrument played primarily with the fingers or thumb, by plucking, slapping, popping, tapping, thumping, or picking with a plectrum, often known as a pick. The bass guitar is similar in appearance and construction to an electric guitar, but with a longer neck and scale length, and four to six strings or courses. The four-string bass—by far the most common—is usually tuned the same as the double bass, which corresponds to pitches an octave lower than the four lowest pitched strings of a guitar (E, A, D, and G). The bass guitar is a transposing instrument, as it is notated in bass clef an octave higher than it sounds (as is the double bass) to avoid excessive ledger lines. Like the electric guitar, the bass guitar is plugged into an amplifier and speaker for live performances.",
			"image"	:  "Bass",
			"price" : "35.98",
			"specifications" : "Specifications of ",
			"dateAdded" : "1402544423000",
			"category" : "cheap",
			"soldOut" : "false",
			"reviews" : [{
					"star" : "5",
					"body" : "Its awesome guitar.",
					"name" : "Obama"
				},
				{
					"star" : "4.3",
					"body" : "Simple and elegand. Do buy this!!",
					"name" : "Ray"
				}]
		},
		{
			"name" 		 : "Violin / Fiddle",
			"description": "Buynig Violin offers video instruction for beginning and advanced violinists.",
			"longDescription" : "The violin, also known as a fiddle, is a string instrument, usually with four strings tuned in perfect fifths. It is the smallest, highest-pitched member of the violin family of string instruments, which also includes the viola, the cello and the double bass. Someone who plays the violin is called a violinist or a fiddler. The violinist produces sound by drawing a bow across one or more strings (which may be stopped by the fingers of the other hand to produce a full range of pitches), by plucking the strings (with either hand), or by a variety of other techniques. The violin is played by musicians in a wide variety of musical genres, including Baroque music, classical, jazz, folk music, rock and roll, and soft rock. The violin has come to be played in many non-Western music cultures all over the world.",
			"image"	:  "Violin",
			"price" : "20.98",
			"specifications" : "Specifications of ",
			"dateAdded" : "1404193680000",
			"category" : "Expensive",
			"soldOut" : "true",
			"reviews" : [{
					"star" : "1",
					"body" : "Its horrible dont buy this violin ever.",
					"name" : "Arnold"
				},
				{
					"star" : "2",
					"body" : "It reminds me of my grandma's old car!!",
					"name" : "Mark"
				}]
		}
]

As you can see, in each guitar there are now nested reviews in each guitar item. That pretty much it, just added some more data.

Second

We know that where our review tab content is. If you don’t know, it is in details.html file here :

<div ng-show="panel.isSelected(3)">
...
</div>

Lets replace this with following code in our review tab for angularjs form validation example to work like this:

<!-- Review Tab START, it has a new controller -->
<div ng-show="panel.isSelected(3)" class="reviewContainer" ng-controller="ReviewController as reviewCtrl" >
				
	<!-- User Reviews on each guitar from data.json - simple iterating through guitars list -->
	<div class="longDescription uReview" ng-repeat="review in guitarVariable[whichGuitar].reviews"> 
		<h3>Review Points: {{review.star}} </h3>
		<p> {{review.body}} ~{{review.name}} on <date>{{review.createdOn | date:'MM/yy'}} </p>
	</div><!-- End User Reviews -->

	<!-- This is showing new review preview-->
	<div ng-show="add === 1" class="longDescription uReview" > 
		<h3>Review Points: {{reviewCtrl.review.star}} <span ng-click="add=0">X</span></h3>
		<p> {{reviewCtrl.review.body}} ~ {{reviewCtrl.review.name}} </p>
	</div>

	<!-- Add new Review to specific guitar - click this link to show review adding pannel -->
	<a href ng-click="add=1" class="addReviewLink">Add review</a>	

	<!-- form validates here using form name and .$valid and on submission we are going to addReview function with guitarID -->
	<form class="reviewForm" name="reviewForm" ng-submit="reviewForm.$valid && reviewCtrl.addReview(guitarVariable.indexOf(guitarVariable[whichGuitar]))" novalidate ng-show="add===1" >
		<div>
			Review Points: 
			<!-- ng-option here is setting options, cool? -->
			<select ng-model="reviewCtrl.review.star" ng-options="point for point in [5,4,3,2,1]" required >				</select>
			Email: 
			<input type="email" ng-model="reviewCtrl.review.name" required>
			<button type="submit">Submit</button>
		</div>
		<textarea placeholder="Enter your experience with this guitar..."  ng-model="reviewCtrl.review.body"></textarea>
	</form><!-- END add new review -->
</div><br /><!-- END Review Tab -->

Code Explanation:

Line 2:  ng-show says, show this div only when isSelected === 3 (It is explained in previous tutorial). Next, associated this div with ReviewController and gave it an alias of reviewCtrl (will define it shortly in controllers.js file) Line 5: ng-repeat is different here than the one we used earlier, if you goto data.json file and look for reviews you will find out that it is nested inside each guitar. In easy words, for each guitar in data.json there are multiple reviews. So it says, for each guitar’s review in reviews array, show the data where it requires. Line 10: this div is only visible when add review is clicked. when add review is clicked, add value is set to 1 and it becomes visible. Line 20: here I defined the form name because I want to validate the form using its name and angularjs built in $valid magic keyword. And also on submission of form I want to goto a function with information  of current/selected guitar I am on. Next, I don’t want my html to validate form for me, since I am interested in validating it through angularjs way using $valid. Finally, I want it to be visible only when anchor tag above is clicked and its value is set to 1. Line 24: defined ng-model, because I want my input to appear directly in new review tab as soon as I type (line 11). Next, in select tag instead of typing in 5 options I used a simple trick of ng-option to put necessary options into select. Thats it. Lets run it in firefox. Goto details page then review then click on add review…

Third

One more thing is, you need to update style.css file too. Download and replace the existing file with this one: styles.css (updated) If you open the new styles.css file and goto end of it you will find some css styles like this:

.ng-invalid.ng-dirty {
	border-color: red;
	box-shadow: 0px 0px 2px red;
}
.ng-valid.ng-dirty {
	border-color: #06B306;
	box-shadow: 0px 0px 2px #06B306;
}

These class styles are added by angularjs validation to form when we insert that $valid keyword to our form. Also notice that these styles don’t have space in them, this is because we are saying add style to that element which has both of these classes in it. ng-invalid means when for example wrong email format is insert it will highlight it with red border. ng-dirty is activated once we write something opposite of it is ng-prestine.

Finally

We are going to make our controller in controllers.js file at the end like this:

GuitarControllers.controller('ReviewController', function (){
	this.review = {};

	this.addReview = function(guitarID){
		//this.review.createdOn = Date.now();
		guitarID.reviews.push(this.review);
		this.review = {};
	};
});

Code Explanation:

Line 2: setting up an empty object here. Line 6: just pushing the guitar review to its review array in data.json So far, I have added some styles in css file and added a controller and some form/stuff in details.html page. Although, this is not fully functional right now (will make it more practical in next tutorial) but some how you know how to do form validation in our angularjs guitar application.

Demo

click on review tab and then click on add review… input something and see what happens also notice that input fields borders are changing. Right now submit button isn’t configured properly, will do it in next tutorial.

Video Tutorial

 

Download Project Files Hope you like it. Please share my work.

next-AngularJS MVCPrevious-Chapter-Button

//

27 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *