AngularJS/HTML5:フォームバリデーションのサンプルコード

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

AngularJS/HTML5を使う時のフォームバリデーションの方法、メモとしてサンプルコードを書いています。

HTML5のフォームバリデーション

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>


HTML5のフォームバリデーション機能を無効にしたい場合(AngularJSの機能にてバリデーションを行う時など)には novalidate を追加する。

<form name="sampleform" novalidate>


required で入力必須にしているけれども Submit ボタンを押せるようにしたい場合には formnovalidate を追加するらしいです。

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

AngularJSのフォームバリデーション

まずテストであっても ng-model だけは書いておかないと、AngularJSのフォームバリデーションは動作しません


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

form に novalidate を追加することによって、HTML5とAngularJSのバリデーションがコンフリクトしないようにします。

バリデーションエラーの表示は ng-messages を使う方法もあるみたいですが、上記のサンプルでは ng-show で表示させています。

submit ボタンに ng-disabled を設定することによって、バリデーションエラーが発生していると submit ボタンが有効にならないようにすることができます。

No tags for this post.

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