做了一个js正则表达式验证姓名、邮箱、手机号的小功能,记录下来,以备后续学习之用。
html代码:
<div class="lx_xx">
<p><h3>联系信息</h3></p> <ul> <li> <span class="font_color1">*</span> 姓名: <input type="text" class="np_e" name="contact_name"/> <span class="font_color1" style="display:none;">*请填写您的姓名</span> </li> <li> <span class="font_color1">*</span> 电话: <input type="text" class="np_e" name="contact_phone"/> <span class="font_color1" style="display:none;">*请填写您的手机号并保持畅通</span> </li> <li> <span class="font_color1">*</span> 邮箱: <input type="text" class="np_e" name="contact_email"/> <span class="font_color1" style="display:none;">*请填写您的邮箱以便订购成功后收取邮件</span> </li> <li>补充说明: <textarea class="textarea_bg" name="explain">请描述您的其他要求</textarea> </li> </ul></div>js代码:
$(document).ready(function(){
$(".np_e").bind('blur',function(){ if($.trim($(this).val()) == ''){ if($(this).attr('name') == 'contact_phone'){ $(this).next('.font_color1').html('*请填写您的手机号并保持畅通'); } if($(this).attr('name') == 'contact_name'){ $(this).next('.font_color1').html('*请填写您的姓名'); } if($(this).attr('name') == 'contact_email'){ $(this).next('.font_color1').html('*请填写您的邮箱以便订购成功后收取邮件'); } $(this).next('.font_color1').show(); }else{ if($(this).attr('name') == 'contact_phone'){ var telNum = $.trim($(this).val()); var reg = /^1((3[0-9])||(5[0-3])||(5[5-9])||(8[5-9])||(80)||(82)||(47))\d{8}$/g; //手机号正则验证 if (isNaN(telNum) || telNum.length != 11) { $(this).next('.font_color1').html("*手机号码为11位,请正确填写!"); $(this).next('.font_color1').show(); return false; } if (!reg.test(telNum)) { $(this).next('.font_color1').html("*请输入合法的手机号码!"); $(this).next('.font_color1').show(); return false; } } if($(this).attr('name') == 'contact_name'){ var conName = $.trim($(this).val()); var reg_name = /^[\u4e00-\u9fa5a-zA-Z]+$/; if(!reg_name.test(conName)){ $(this).next('.font_color1').html("*请输入正确的姓名!"); $(this).next('.font_color1').show(); return false; } } if($(this).attr('name') == 'contact_email'){ var conEmail = $.trim($(this).val()); var reg_email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; if(!reg_email.test(conEmail)){ $(this).next('.font_color1').html("*请输入正确的邮箱地址!"); $(this).next('.font_color1').show(); return false; } } } }); $(".np_e").bind('focus',function(){ $(this).next('.font_color1').hide(); }); $("textarea[name='explain']").bind('focus',function(){ $(this).css('color','#333'); if($(this).val() == '请描述您的其他要求'){ $(this).val(""); } }); $("textarea[name='explain']").bind('blur',function(){ if($(this).val() == ''){ $(this).css('color','rgb(189,189,189)'); $(this).val('请描述您的其他要求'); }else{ } });});