# jQueryでフォームのバリデート

- リンク: https://torounit.com/blog/jquery%e3%81%a7%e3%83%95%e3%82%a9%e3%83%bc%e3%83%a0%e3%81%ae%e3%83%90%e3%83%aa%e3%83%87%e3%83%bc%e3%83%88/
- 公開日: 2011-03-22T16:38:19+09:00
- 作成者: Toro\_Unit

[bassistance.de » jQuery plugin: Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)

とかjQueryでフォームの入力チェックのプラグインは高機能なものがあるのですが、勉強
ついでに作ってみました。

# スクリプト本体

[js]
 jQuery(function($) { jQuery.fn.extend({ showErr:function(){ var self = $(this);

 $(".err").hover(function(){
 $(this).fadeOut("slow",function(){$(this).remove();});});
self.next().css({left:self.position().left+self.width()-15+"px",top:self.position().
top-8+"px"}).fadeIn("slow"); } });

 jQuery.fn.extend({
 fadeRemove:function(){ $(this).fadeOut("slow",function(){$(
this).remove();}); } });

 jQuery.fn.extend({
 chkRequired:function(){ var self = $(this); var err = self.
find(" ~ .noValue"); if(!self.attr("value")){ if(!err.length){ self.after(‘<div 
class="err noValue">必須項目です。</div>’); self.showErr(); } return 1;

 }else{
 err.fadeRemove(); } return false; } });

 jQuery.fn.extend({
 chkAddress:function(){ var self = $(this); var err = self.find("
~ .invalidateAddress"); if(self.attr("value")){ if(!self.attr("value").match(/[!#-
9A-~]+@+[a-z0-9]+.+[^.]$/i)){ if(!err.length){ self.after(‘<div class="err invalidateAddress"
>メールアドレスが正しくありません。</div>’); self.showErr(); } return 1;

 }else{
 err.fadeRemove();

 }
 }else{ err.fadeRemove(); } return false; } }); }); [/js]

# 使い方

こんな感じでメールフォームなどで使います。

[js]
 $(function(){

 $(":input").focusout(function(){
 $(this).chkRequired(); $(this).filter(".email").
chkAddress(); });

 $("form").submit(function(){
 var err = 0; $(":input").each(function(){ err +=$(
this).chkRequired(); err +=$(this).filter(".email").chkAddress(); }); if(!err){ 
$.ajax(‘mail.php’,{ type:"post", data:$("form").serialize(), success:function(html){
$("#response").html(html); }; });

 }
 return false; });

});

[/js]
