在日常工作中,很多时候需要表单验证。在下面这个表单中,需求是:在输入框失去焦点时验证所填入的手机号码。点击输入框后面的⊕可以进行下一个手机号码的输入并验证。
html代码:
1 <table id="addCustomer"> 2 <tr> 3 <td class="w70">客户姓名</td> 4 <td> 5 <input type="text" id="pc_name" name="pc_name"> 6 </td> 7 <td class="w70">客户编号</td> 8 <td><input type="text" name="pc_csrid"></td> 9 <td class="w70">客户等级</td> 10 <td> 11 <select id="pc_grade" name="pc_grade"> 12 <option value="1">非常重要</option> 13 <option value="2">重要</option> 14 <option value="3">一般</option> 15 </select> 16 </td> 17 </tr> 18 <tr> 19 <td class="w70">联系手机</td> 20 <td class="phone_td" colspan="5"><input type="text" id="pc_mphone" name="pc_mphone"><label id="add_phone" style="font-size:20px;font-weight: bold;color: #58799a;">⊕</label></td> 21 </tr> 22 </table>
js代码:
1 $("#pc_mphone").blur(function () { 2 phone = this.value; 3 RegCellPhone = /^([1][0-9]{10})?$/; 4 falg=phone.search(RegCellPhone); 5 if (falg==-1){ 6 alert("手机号不合法!"); 7 $("#pc_mphone").val(""); 8 // this.focus(); 9 }else{ 10 $("#add_phone").click(function(){ 11 if($("#pc_mphone").val()!==""){ 12 $("#pc_mphone").parent().prepend("<label><input value="+$("#pc_mphone").val()+" name=\"ic_phone\" style=\"border:0;width:80px;background:#fff\" disabled/><label class=\"del\" style=\"color:red;font-weight: bold;\">×</label>,</label>"); 13 $("#pc_mphone").val(""); 14 $(".del").click(function(){ 15 $(this).parent("label").remove(); 16 }) 17 } 18 19 }); 20 21 } 22 });
界面: