JavaScript表单数据验证 onclick()
作者:Alpha时间:2017-09-14 阅读数:2710 +人阅读
表单提交验证,提交前先通过JavaScript验证下手机号和姓名,此处记录的方法未采用ajax进行数据提交。
表单代码如下:
<form action="do.php" onSubmit="return submits(2);" enctype="multipart/form-data" method="post"> <p class="banner_info_shuru"> <input type="text" value="" name="name" class="attr" placeholder="姓名" id="name2"> </p> <div class="space"></div> <p class="banner_info_shuru"> <input type="text" value="" name="phone" class="attr" placeholder="手机号码" id="mobile2"> </p> <div class="space"></div> <p class="banner_info_shuru"> <input type="text" value="项目类型" name="content" class="attr" dvalue="项目类型" id="xiangmu2"> </p> <input type="hidden" name='riqi' id='shijian0' style='width:250px' class='intxt' value='' /> <script>var d=new Date();riqi=d.toLocaleString(); $("#shijian").val(riqi);</script> <p><input type="submit" name="submit" value="立即预约" class='banner_yuyue_btn' /></p> </form>
form处设置了onSubmit="return submits()"属性,当点击submit提交按钮后,会先触发这个函数,该函数就是一个JavaScript方法。
代码如下:
function submits(type) { console.log(type); name=$("#name"+type).val(); phone=$("#mobile"+type).val(); if(checkName(name,type)){ }else { return false; } if(checkMobile(phone,type)){ }else{ return false; } }pe) {
上述代码中用到了两个方法checkName()和checkMobile(),具体代码如下:
checkName:
//检查姓名 function checkName(name,type){ var len = getStrlen(name); $("#err_box"+type).html(""); if(len == 0){ $("#name"+type).focus(); $("#err_box"+type).html("姓名不能为空"); return false; } if(len > 5){ $("#name"+type).focus(); $("#err_box"+type).html("姓名不能超过5个字"); return false; } return true; }
checkMobile:
//检查联系方式 function checkMobile(mobile,type){ $("#err_box"+type).html(""); if(mobile == ''){ $("#mobile"+type).focus(); $("#err_box"+type).html("手机号不能为空"); return false; } if(mobile != ''){ var isMob=/^1[3-5,7,8]{1}[0-9]{9}$/; if(!isMob.test(mobile)){ $("#mobile"+type).focus(); $("#err_box"+type).html("手机号格式不正确"); return false; } } return true; }
上面的type参数和id='name2'对应的,当同一页面中需要有两个以上验证的时候,通过type值的不同来获取对应不同的id值。
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:595397166@qq.com