直接上代码:
电话号码:<input type="text" id="TelPrefix" size="4" MaxLength="4"> - <input type="text" id="TelNumber" style="width:88px"> <button id="btnTestTel" onClick="return TestTel()">测试电话号码</button> <br/> 手机号码:<input type="text" id="Mobile"> <button id="btnTestMobile" onClick="return TestMobile()">测试手机号码</button> <br/><br/>
建议手机号码与电话号码至少请输入一项<br/><br/>
<button id="btnTest" onClick="return Test()">测试手机号码</button>
js代码:
<script type="text/javascript"> String.prototype.Trim = function() { var m = this.match(/^\s*(\S+(\s+\S+)*)\s*$/); return (m == null) ? "" : m[1]; } String.prototype.isMobile = function() { return (/^(?:13\d|15[89])-?\d{5}(\d{3}|\*{3})$/.test(this.Trim())); } String.prototype.isTel = function() { return (/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/.test(this.Trim())); } function TestMobile() { var oMobile = document.getElementById("Mobile"); if (!oMobile.value.isMobile()) { alert("请输入正确的手机号码"); oMobile.focus(); oMobile.style.backgroundColor="#ff9"; return false; } else { alert(oMobile.value); } return true; } function TestMobileEx() { var oMobile = document.getElementById("Mobile"); if (!oMobile.value.isMobile()) { return false; } return true; } function TestTel() { var oTelPrefix = document.getElementById("TelPrefix"); var oTelNumber = document.getElementById("TelNumber"); var sTel = oTelPrefix.value + "-" + oTelNumber.value; if (!sTel.isTel()) { alert("请输入正确的电话号码"); oTelPrefix.focus(); oTelPrefix.style.backgroundColor="#ff9"; oTelNumber.style.backgroundColor="#ff9"; return false; } else { alert(sTel); } return true; } function TestTelEx() { var oTelPrefix = document.getElementById("TelPrefix"); var oTelNumber = document.getElementById("TelNumber"); var sTel = oTelPrefix.value + "-" + oTelNumber.value; if (!sTel.isTel()) { return false; } return true; } function Test() { if (TestTelEx()||TestMobileEx()) { alert("验证通过"); } else { alert("手机,电话至少输入一项"); document.getElementById("TelPrefix").focus(); document.getElementById("TelPrefix").style.backgroundColor="#ff9"; return false; } return true; } </script>