主要包括必選字段、手機號、電子郵箱、兩次輸入是否一致等4種驗證。
一、引入zepto.js。zepto.js下載地址:zepto.js
二、js代碼庫以下:css
jsvar validate = { require: function(elem, errmsg){ elem = $(elem); elem.on("change", function(){ var value = this.value; alert("value:"+value); var tipCon = $(this).parents("td").find("span"); alert("tipCon:"+tipCon.length); if(value == ""){ tipCon.html(errmsg); }else{ tipCon.html(""); } }); }, phone: function(elem, errmsg){ elem = $(elem); var tipCon = elem.parent().find("span"); elem.on("change", function(){ var value = $.trim(this.value); if(!/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[0-9])[0-9]{8}$/.test(value)){ tipCon.html(errmsg); }else{ tipCon.html(""); } }); }, email: function(elem, errmsg){ elem = $(elem); var tipCon = elem.parent().find("span"); elem.on("change", function(){ var value = $.trim(this.value); if(!/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)){ tipCon.html(errmsg); }else{ tipCon.html(""); } }); }, compare: function(elem1, elem2, errmsg){ elem1 = $(elem1); elem2 = $(elem2); var tipCon = elem2.parent().find("span"); elem2.on("change", function(){ var value1 = $.trim(elem1[0].value); var value2 = $.trim(this.value); if(value1 !== value2){ tipCon.html(errmsg); }else{ tipCon.html(""); } }); } };
三、該類的使用辦法:html
js//驗證 (function(){ //驗證必填字段 var requireArr = [ { id: "user", errmsg: "姓名不能爲空" }, { id: "company", errmsg: "公司名稱不能爲空" }, { id: "area", errmsg: "國家/地區不能爲空" } ]; $.each(requireArr, function(i, obj){ validate.require("#"+obj.id, obj.errmsg); }); validate.phone("#phone", "手機號碼格式不正確"); validate.email("#email", "電子郵箱格式不正確"); validate.compare("#email", "#email-c", "兩次郵箱不一致"); });
截圖:
ui
一、html代碼this
html<label for="bill_y" class="r-label checked"><label for="bill_n" class="r-label"><input type="radio" name="bill" id="bill_n"/>否</label>
二、css代碼url
input[type=radio]{ width: .975rem; visibility: hidden; vertical-align: middle; } .r-label{ display: inline-block; height: 1.55rem; background: url("../img/radio.png") left center no-repeat; background-size: 0.975rem 0.975rem; padding-left: 0.45rem; } .r-label.checked{ background: url("../img/radio-checked.png") left center no-repeat; background-size: 0.975rem 0.975rem; }
三、js代碼spa
//處理單選框選中 $(".r-label").on("tap",function(){ var $this = $(this); var $radio = $(this).find("input[type=radio]"); var checked = $radio.prop("checked"); if(!checked && !$this.hasClass("checked")){ $(".r-label").removeClass("checked"); $this.addClass("checked"); } });