AngularJS/HTML5:Sample Code of Form Validation

Published on:
Last updated:

Sponsored Links

This post is also available in: Japanese

This article is about how to write form validation code when you use AngularJS/HTML5.

HTML5 Form Validation(required)

web_HTMLvalidate

<form name="sampleform">
	<input type="text" name="fk" placeholder="First Keywords" pattern="[a-zA-z]" title="AAAAAAAAAAAAAA" required />
	<input type="text" name="sk" placeholder="Second Keywords" pattern="[a-zA-z]" title="BBBBBBBBBBBBBB" required />
	<input type="submit" value="Submit!"  required />
</form>


If you want to disable the HTML5 form validation, add “novalidate”. (such as when you use the validation in the function of AngularJS)

<form name="sampleform" novalidate>


If you want to activate the submit button although have the “required” input, add a “formnovalidate”.

<input type="submit" value="Submit!" formnovalidate />

AngularJS Form Validation

First,if you do not write “ng-model”, form validation of AngularJS will not work.

<form name="sampleform" ng-controller="SampleCtrl" ng-submit="submit()" novalidate>
	<label>
		<input type="text" name="fk" ng-model="sample.fk" placeholder="First Keywords" required ng-pattern="/^[a-zA-z]*$/" ng-trim="false" />
	</label>
	<div class="error" ng-show="sampleform.$invalid">
		<small class="error" ng-show="sampleform.fk.$error.required">Required!</small>
		<small class="error" ng-show="sampleform.fk.$error.pattern">Alphabet Words Only!</small>
	</div>
	<label>
		<input type="text" name="sk" ng-model="sample.sk" placeholder="Second Keywords" required ng-pattern="/^[a-zA-z]*$/" ng-trim="false" />
	</label>
	<div class="error" ng-show="sampleform.$invalid">
		<small class="error" ng-show="sampleform.sk.$error.required">Required!</small>
		<small class="error" ng-show="sampleform.sk.$error.pattern">Alphabet Words Only!</small>
	</div>
	<input type="submit" ng-disabled="!sampleform.$valid" value="Generate!" required />
	<!-- start test -->
	<p>{{sampleform.$valid}}</p>
	<p>{{sampleform.$dirty}}</p>
	<!-- end test -->
</form>

By adding a “novalidate” to form, you can avoid conflict validation of HTML5 and AngularJS .

There is also a method using the “ng-messages” to display the validation error, but in the above sample using ng-show.

By setting the “ng-disabled” to submit button, you can avoid active when the validation error has occurred.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and connect with me on Google+,LinkedIn(English).


Sponsored Links