この記事は年以上前に書かれたもので、内容が古かったり、セキュリティ上の問題等の理由でリンクが解除されている可能性があります。
フォームバリデーション系のプラグインは
既に数多く良質なものが揃っているので、
今更、という気もしますが、自分と相性が
良さそうだったので備忘録。軽量でシンプル
で、カスタマイズもしやすかったです。
高機能ではなくていいので、こういうのが
欲しいんですよね・・
もちろん、クロスブラウザで動作してくれます。圧縮すれば2KB以下にまで落とせる軽量ライブラリです。
validate.js

バリデーション用のライブラリです。軽量でクロスブラウザ対応。コードもシンプルでカスタマイズしやすい印象でした。
サンプルです。エラーメッセージは適当なので気にしないで下さい。
Sample
コード
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="validate.js"></script>
jQuery本体とプラグインを読み込みます。
で、バリデーションのルールを書く。フォームのname属性と合わせて書いていきます。
<script type="text/javascript">
new FormValidator('example_form', [{
name: 'req',
display: 'required',
rules: 'required'
}, {
name: 'alphanumeric',
rules: 'alpha_numeric'
}, {
name: 'パスワード',
rules: 'required'
}, {
name: 'password_confirm',
display: 'パスワード再入力',
rules: 'required|matches[password]'
}, {
name: 'email',
rules: 'valid_email'
}, {
name: 'minlength',
display: 'メールアドレスの隣の項目',
rules: 'min_length[8]'
}, {
name: 'tos_checkbox',
display: 'チェックボックス',
rules: 'required'
}], function(errors, event) {
var SELECTOR_ERRORS = $('.error_box'),
SELECTOR_SUCCESS = $('.success_box');
if (errors.length > 0) {
SELECTOR_ERRORS.empty();
SELECTOR_ERRORS.append(errors.join('<br />'));
SELECTOR_SUCCESS.css({ display: 'none' });
SELECTOR_ERRORS.fadeIn(200);
} else {
SELECTOR_ERRORS.css({ display: 'none' });
SELECTOR_SUCCESS.fadeIn(200);
}
if (event && event.preventDefault) {
event.preventDefault();
} else if (event) {
event.returnValue = false;
}
});
</script>
表示させるエラーメッセージはvalidate.js内を変更します。
15行目あたり。
var defaults = {
messages: {
required: 'The %s field is required.',
matches: 'The %s field does not match the %s field.',
valid_email: 'The %s field must contain a valid email address.',
min_length: 'The %s field must be at least %s characters in length.',
max_length: 'The %s field must not exceed %s characters in length.',
exact_length: 'The %s field must be exactly %s characters in length.',
greater_than: 'The %s field must contain a number greater than %s.',
less_than: 'The %s field must contain a number less than %s.',
alpha: 'The %s field must only contain alphabetical characters.',
alpha_numeric: 'The %s field must only contain alpha-numeric characters.',
alpha_dash: 'The %s field must only contain alpha-numeric characters, underscores, and dashes.',
numeric: 'The %s field must contain only numbers.',
integer: 'The %s field must contain an integer.'
},
ルールに合わせてメッセージを便宜変更します。
よく分からないようでしたら先程のサンプルのソースをご参考下さい。適当ですけどw
ライブラリは以下でどうぞ。
validate.js

