function Checkreg() { //驗證電話號碼手機號碼,包含153,159號段 if (document.form.phone.value=="" && document.form.UserMobile.value==""){ alert("電話號碼和手機號碼至少選填一個阿!"); document.form.phone.focus(); return false; } if (document.form.phone.value != ""){ var phone=document.form.phone.value; var p1 = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/; var me = false; if (p1.test(phone))me=true; if (!me){ document.form.phone.value=''; alert('對不起,您輸入的電話號碼有錯誤。區號和電話號碼之間請用-分割'); document.form.phone.focus(); return false; } } if (document.form.UserMobile.value != ""){ var mobile=document.form.UserMobile.value; var reg0 = /^13\d{5,9}$/; var reg1 = /^153\d{4,8}$/; var reg2 = /^159\d{4,8}$/; var reg3 = /^0\d{10,11}$/; var my = false; if (reg0.test(mobile))my=true; if (reg1.test(mobile))my=true; if (reg2.test(mobile))my=true; if (reg3.test(mobile))my=true; if (!my){ document.form.UserMobile.value=''; alert('對不起,您輸入的手機或小靈通號碼有錯誤。'); document.form.UserMobile.focus(); return false; } return true; } }
說明
test方法檢查在字符串中是否存在一個模式,如果存在則返回 true,否則就返回 false。
正則表達式部分:
\d 代表一個數字
{7,8} 代表7-8位數字(表示電話號碼)
{3,} 代表分機號碼
d{2,3} 代表區號
\+]\d{2,3} 代表國際區號
^13\d{5,9}$/ //130?139。至少5位,最多9位
/^153\d{4,8}$/ //聯通153。至少4位,最多8位
/^159\d{4,8}$/ //移動159。至少4位,最多8位
第二個:
代碼如下:
var Mobile = $("#varMobilePhone").val(); var Phone = $("#varPhoneNo").val(); if (Mobile == ""&&Phone == "") { alert("手機和固話,請至少填寫一項聯系方式!"); $("#varMobilePhone").focus(); return; } if(Mobile!="") { if(!isMobil(Mobile)) { alert("請輸入正確的手機號碼!"); $("#varMobilePhone").focus(); return; } } //手機號碼驗證信息 function isMobil(s) { var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/; if (!patrn.exec(s)) { return false; } return true; } 后台驗證如下: if (model.Zip != null) { if (!Common.PageValidate.IsValidate(model.Zip,"^\\d{6}$")) { Common.WebMessage.showMsg(HttpContext.Current, "請輸入正確郵編"); return; } } if (model.PhoneNo != null) { if (!Common.PageValidate.IsValidate(model.PhoneNo, "\\d{3}-\\d{8}|\\d{4}-\\d{7}")) { Common.WebMessage.showMsg(HttpContext.Current, "請輸入正確的電話號碼!"); return; } } if (model.MobilePhone != null) { if (!Common.PageValidate.IsValidate(model.MobilePhone, "^0{0,1}(13[0-9]|15[3-9]|15[0-2]|18[0-9])[0-9]{8}$")) { Common.WebMessage.showMsg(HttpContext.Current, "請輸入正確11位有效的手機號碼!"); return; } }