項(xiàng)目需求:
輸入手機(jī)號(hào),實(shí)時(shí)判斷手機(jī)號(hào)輸入的是否符合規(guī)則:
如果不合規(guī)則,則提交按鈕為禁用狀態(tài),手機(jī)號(hào)信息不可提交,按鈕顯示灰色背景;
如果符合規(guī)則,則可提交所輸入的手機(jī)號(hào)信息,并將按鈕背景設(shè)成紅色。
代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 400px; margin: 50px auto; border: 1px solid #ccc; padding: 50px; } #phone{ text-align: center; margin-bottom: 20px; border: 1px solid #ccc; color: #333; } .submit, .disable, #phone{ display: block; width: 190px; height: 35px; border-radius: 5px; margin-left:auto; margin-right:auto; } .disable{ border: none; background-color: #ccc; color: #fff; } .submit{ border: none; background-color: red; color: #fff; } </style></head><body> <div class="box"> <input id="phone" type="text" placeholder="輸入領(lǐng)券手機(jī)號(hào)" maxlength="11"> <button id="submit" class="disable" disabled>確認(rèn)領(lǐng)取</button> </div> <script src="jquery.min.js"></script> <script> $(function () { var $phone = $('#phone'); var $submit = $('#submit'); $phone.on('input propertychange', function () { var phone = this.value; if (/^((13[0-9]|15[0-9]|17[0-9]|18[0-9])+/d{8})$/.test(phone)) { $submit.removeClass('disable').addClass('submit').removeAttr('disabled'); } else { $submit.removeClass('submit').addClass('disable').attr('disabled', 'disabled'); } }); }); </script></body></html>效果:
用戶輸入的手機(jī)號(hào)不合規(guī)則時(shí):

用戶輸入的手機(jī)號(hào)符合規(guī)則時(shí):

ps:jquery驗(yàn)證電話號(hào)碼
var isMobile=/^(?:13/d|15/d|18/d)/d{5}(/d{3}|/*{3})$/; //手機(jī)號(hào)碼驗(yàn)證規(guī)則var isPhone=/^((0/d{2,3})-)?(/d{7,8})(-(/d{3,}))?$/; //座機(jī)驗(yàn)證規(guī)則var dianhua = $("#dianhua").val(); //獲得用戶填寫的號(hào)碼值 賦值給變量dianhuaif(!isMobile.test(dianhua) && !isPhone.test(dianhua)){ //如果用戶輸入的值不同時(shí)滿足手機(jī)號(hào)和座機(jī)號(hào)的正則 alert("請正確填寫電話號(hào)碼,例如:13415764179或0321-4816048"); //就彈出提示信息 $("#dianhua").focus(); //輸入框獲得光標(biāo) return false; //返回一個(gè)錯(cuò)誤,不向下執(zhí)行新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注