jQuery Ajax Submit(Ajax提交表单),加入表单验证

不需要修改html,但验证的时候需要写正则,已经提供了常用的正则表达式,只是写的不太严谨,演示在下面

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//ajax submit by Leon
//正则写的并不严谨,各位可以根据需要自己改一下
function ajaxSubmit(){
    $('.errinfo').remove();//移除上一次的验证提示信息
    var params = {};
    $("input:checked, :text, :hidden, :password,select, textarea").map(function() { 
        if($(this).attr('name')=='name' && $.trim($(this).val())==''){ //验证是否为空
            $(this).parent().append('<span class="errinfo">此项不能为空</span>');
        }else if($(this).attr('name')=='email' && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test($(this).val())){ //验证email
            $(this).parent().append('<span class="errinfo">电子邮件格式不正确</span>');
        }else if($(this).attr('name')=='tel' && !/^(1\d{10})$/.test($(this).val())){  //验证手机号
            $(this).parent().append('<span class="errinfo">手机号码格式不正确</span>');
        }else if($(this).attr('name')=='date' && !/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/.test($(this).val())){  //验证日期格式yyyy-mm-dd
            $(this).parent().append('<span class="errinfo">日期格式不正确</span>');
        }
        params[$(this).attr('name')] = $(this).val();
    }); 
    if($('.errinfo').size()==0){
        $.ajax({
            type:"POST", url:"submit.php", data:params, dataType:"json",
             success: function(data){
                //提交成功后要进行的操作
             },
             error:function(){
                alert('err');
             }
        });
    }
}


演示

Comments (0)

› No comments yet.

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

 :wink:  :-|  :-x  :twisted:  :)  8-O  :(  :roll:  :-P  :oops:  :-o  :mrgreen:  :lol:  :idea:  :-D  :evil:  :cry:  8)  :arrow:  :-?  :?:  :!:

Pingbacks (0)

› No pingbacks yet.