
お問い合わせフォームなどの入力フォームで入力された値をチェックや未入力をチェックする事ができるJavaScriptライブラリ『Validatr』をご紹介します。
『Validatr』はjQueryをベースに開発され、MIT License にて公開さております。電子メール、数字、URL、日付、色などの入力に対してサポートされています。
ダウンロード
実装方法
ライブラリの読込み
『Validatr』はjQuery対応のライブラリなので稼動するためには「jQuery」が読み込まれていることが必要になります。基本的には、以下のライブラリを読込むことで『Validatr』を稼動することができます。
<!-- jQuery -->
<script src="jquery.js"></script>
<!-- Include js plugin -->
<script src="js/validatr.js"></script>
オプション設定・ライブラリの実行
『Validatr』を邸要するフォームを指定します。
jQuery(function ($) {
$('form').validatr();
});
HTML
表示するコンテンツのHTMLソースになります。inputタグにて指定されるtypeの内容に応じたチェックを行うことが出来ます。type には text, checkbox, radio, color, date, email, number, range, url などがあります。
必須項目については「required」をつけることで対応することできます。
<form action="./">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<div>
<input type="reset" class="btn" value="Reset">
<input type="submit" value="Submit">
</div>
</form>
表示メッセージの編集
入力形式が間違っていますなどのエラーメッセージは英文になってますので、日本語にしたい場合は「validatr.js」内のメッセージ内容を書き換えるか、メッセージ用のJavaScriptを記述します。
最初に「validatr.js」の内容を書き換える場合は、以下のメッセージの文章を書き換えます。
/* validatr.js を直接書き換える場合 */
$.validatr.messages = {
checkbox: 'Please check this box if you want to proceed.',
color: 'Please enter a color in the format #xxxxxx',
email: {
single: 'Please enter an email address.',
multiple: 'Please enter a comma separated list of email addresses.'
},
pattern: 'Please match the requested format.',
radio: 'Please select one of these options.',
range: {
base: 'Please enter a {{type}}',
overflow: 'Please enter a {{type}} greater than or equal to {{min}}.',
overUnder: 'Please enter a {{type}} greater than or equal to {{min}}<br> and less than or equal to {{max}}.',
invalid: 'Invalid {{type}}',
underflow: 'Please enter a {{type}} less than or equal to {{max}}.'
},
required: 'Please fill out this field.',
select: 'Please select an item in the list.',
time: 'Please enter a time in the format hh:mm:ss',
url: 'Please enter a url.'
};
「validatr.js」を編集しない場合、以下のようにメッセージを追加をします。
※「validatr.js」を読込んだ後に追加をします。
/* 新しくメッセージを追加する場合 */
(function ($) {
$.extend($.validatr.messages, {
checkbox: 'Please check this box if you want to proceed.',
color: 'Please enter a color in the format #xxxxxx',
email: {
single: 'Please enter an email address.',
multiple: 'Please enter a comma separated list of email addresses.'
},
pattern: 'Please match the requested format.',
radio: 'Please select one of these options.',
range: {
base: 'Please enter a {{type}}',
overflow: 'Please enter a {{type}} greater than or equal to {{min}}.',
overUnder: 'Please enter a {{type}} greater than or equal to {{min}}<br> and less than or equal to {{max}}.',
invalid: 'Invalid {{type}}',
underflow: 'Please enter a {{type}} less than or equal to {{max}}.'
},
required: 'Please fill out this field.',
select: 'Please select an item in the list.',
time: 'Please enter a time in the format hh:mm:ss',
url: 'Please enter a url.'
});
}(jQuery));
以上で、『Validatr』によるフォームの入力チェックを実装することができます。



