html5表單驗證

1.第一步在js中寫方法,放在$(document).ready(function(){})裏面
//需要但沒有填寫區域的提示格式
var enrollBatchForm = $("form[id^='enrollBatchForm']");
enrollBatchForm.each(function(){
var formId = this.id;
var flag = formId.substr(formId.indexOf("_") + 1);
$(this).html5Validate(function() {
//調用保存方法
saveEnrollBatch(flag);//在後臺寫saveEnrollBatch方法
});
});
2.定義一個<form id>
<form action ="" class="xxxx" id="entrollBatchForm_add" name="xxx"></form>
3.在label中定義爲必填項,for=""定義提示內容
<label class="control-label" for="enrollBatchName_add"><span class="required">*</span>招生批次:</label>
4.定義一個submit提交按鈕
<div class="modal-footer">
<button type="Submit" class="btn green ajaxButton">保存</button>
5.html5Validate 接口
// 全局對象,可擴展
OBJREG = {
EMAIL:"^[a-z0-9._%-]+@([a-z0-9-]+\\.)+[a-z]{2,4}$",
NUMBER: "^\\-?\\d+(\\.\\d+)?$",
URL:"^(http|https|ftp)\\:\\/\\/[a-z0-9\\-\\.]+\\.[a-z]{2,3}(:[a-z0-9]*)?\\/?([a-z0-9\\-\\._\\?\\,\\'\\/\\\\\\+&amp;%\\$#\\=~])*$",
TEL:"^1\\d{10}$",
ZIPCODE:"^\\d{6}$",
"prompt": {
radio: "請選擇一個選項",
checkbox: "如果要繼續,請選中此框",
"select": "請選擇列表中的一項",
email: "請輸入電子郵件地址",
url: "請輸入網站地址",
tel: "請輸入手機號碼",
number: "請輸入數值",
date: "請輸入日期",
pattern: "內容格式不符合要求",
empty: "請填寫此字段",
multiple: "多條數據使用逗號分隔"
}
};

$.html5Attr = function(ele, attr) {
if (!ele || !attr) return undefined;
// 爲了向下兼容jQuery 1.4
if (document.querySelector) {
return $(ele).attr(attr);
} else {
// IE6, 7
var ret;
ret = ele.getAttributeNode(attr);
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined;
}
};
$.html5Validate = (function() {
// 驗證需要的子集方法 如是否爲空,是否正則匹配,是否溢出
return {
isSupport: (function() {
return $('<input type="email">').attr("type") === "email";
})(),
isEmpty: function(ele, value) {
value = value || $.html5Attr(ele, "placeholder");
var trimValue = ele.value;
if (ele.type !== "password") {
trimValue = $.trim(trimValue);
}
if (trimValue === "" || trimValue === value) return true;
return false;
},
isRegex: function(ele, regex, params) {
// 原始值和處理值
var inputValue = ele.value, dealValue = inputValue, type = ele.getAttribute("type") + "";
type = type.replace(/\W+$/, "");

if (type !== "password") {
// 密碼不trim前後空格
dealValue = $.trim(inputValue);
if (type !== "text" && type !== "null" && ele.tagName.toLowerCase() != "textarea") {
// 非密碼框和文本框進行全半角轉換
dealValue = DBC2SBC(dealValue);
}
//  文本框值改變,重新賦值
if (dealValue !== inputValue) $(ele).val(dealValue);
}

// 獲取正則表達式,pattern屬性獲取優先,然後通過type類型匹配。注意,不處理爲空的情況
regex = regex || (function() {
return $.html5Attr(ele, "pattern");
})() || (function() {
// 文本框類型處理,可能有管道符——多類型重疊,如手機或郵箱
return type && $.map(type.split("|"), function(typeSplit) {
var matchRegex = OBJREG[typeSplit.toUpperCase()];
if (matchRegex) return matchRegex;
}).join("|");
})();

if (dealValue === "" || !regex) return true;

// multiple多數據的處理
var isMultiple = $(ele).hasProp("multiple"), newRegExp = new RegExp(regex, params || 'i');
// number類型下multiple是無效的
if (isMultiple && !/^number|range$/i.test(type)) {
var isAllPass = true;
$.each(dealValue.split(","), function(i, partValue) {
partValue = $.trim(partValue);
if (isAllPass && !newRegExp.test(partValue)) {
isAllPass = false;
}
});
return isAllPass;
} else {
return newRegExp.test(dealValue);
}
return true;
},
isOverflow: function(ele) {
if (!ele) return false;
//  大小限制
var attrMin = $(ele).attr("min"), attrMax = $(ele).attr("max"), attrStep
// 長度限制
, attrDataMin, attrDataMax
// 值
, value = ele.value;

if (!attrMin && !attrMax) {
attrDataMin = $(ele).attr("data-min"), attrDataMax = $(ele).attr("data-max");
if (attrDataMin && value.length < attrDataMin) {
$(ele).testRemind("至少輸入" + attrDataMin + "個字符");
ele.focus();
} else if (attrDataMax && value.length > attrDataMax) {
$(ele).testRemind("最多輸入" + attrDataMax + "個字符");
$(ele).selectRange(attrDataMax, value.length);
} else {
return false;
}
} else {
// 數值大小限制
value = Number(value);
attrStep = Number($(ele).attr("step")) || 1;
if (attrMin && value < attrMin) {
$(ele).testRemind("值必須大於或等於" + attrMin);
} else if (attrMax && value > attrMax) {
$(ele).testRemind("值必須小於或等於" + attrMax);
} else if (attrStep && !/^\d+(\.0+)?$/.test((Math.abs((value - attrMin || 0)) / attrStep).toFixed(10))) {
$(ele).testRemind("值無效");
} else {
return false;
}
ele.focus();
ele.select();
}
return true;
},
isAllpass: function(elements, options) {
if (!elements) return true;
var defaults = {
// 優先label標籤作爲提示文字
labelDrive: true
};
params = $.extend({}, defaults, options || {});

if (elements.size && elements.size() == 1 && elements.get(0).tagName.toLowerCase() == "form") {
elements = elements.find(":input");
} else if (elements.tagName && elements.tagName.toLowerCase() == "form") {
elements = $(elements).find(":input");
}
var self = this;
var allpass = true
 , remind = function(control, type, tag) {
var key = $(control).attr("data-key"), label = $("label[for='"+ control.id +"']"), text= '', placeholder;

if (params.labelDrive) {
placeholder = $.html5Attr(control, "placeholder");
label.each(function() {
var txtLabel = $(this).text();
if (txtLabel !== placeholder) {
text += txtLabel.replace(/\*|:|:/g, "");
}
});
}

// 如果元素完全顯示
if ($(control).isVisible()) {
if (type == "radio" || type == "checkbox") {
$(control).testRemind(OBJREG.prompt[type], {
align: "left"
});
control.focus();
} else if (tag == "select" || tag == "empty") {
// 下拉值爲空或文本框文本域等爲空
$(control).testRemind((tag == "empty" && text)? "您尚未輸入"+ text : OBJREG.prompt[tag]);
control.focus();
} else if (/^range|number$/i.test(type) && Number(control.value)) {
// 整數值與數值的特殊提示
$(control).testRemind("值無效");
control.focus();
control.select();
} else {
// 文本框文本域格式不準確
// 提示文字的獲取
var finalText = OBJREG.prompt[type] || OBJREG.prompt["pattern"];
if (text) {
finalText = "您輸入的"+ text +"格式不準確";
}
if (type != "number" && $(control).hasProp("multiple")) {
finalText += "," + OBJREG.prompt["multiple"];
}

$(control).testRemind(finalText);
control.focus();
control.select();
}
} else {
// 元素隱藏,尋找關聯提示元素, 並走label提示流(radio, checkbox除外)
var selector = $(control).attr("data-target");
var target = $("#" + selector);
if (target.size() == 0) {
target = $("." + selector);
}
var customTxt = "您尚未" + (key || (tag == "empty"? "輸入": "選擇")) + ((!/^radio|checkbox$/i.test(type) && text) || "該項內容");
if (target.size()) {
if (target.offset().top < $(window).scrollTop()) {
$(window).scrollTop(target.offset().top - 50);
}
target.testRemind(customTxt);
} else {
alert(customTxt);
}
}
return false;
};

elements.each(function(){
var el = this, type = el.getAttribute("type"), tag = el.tagName.toLowerCase(), isRequired = $(this).hasProp("required");
// type類型
if (type) {
var typeReplace = type.replace(/\W+$/, "");
if (!params.hasTypeNormally && $.html5Validate.isSupport && type != typeReplace) {
// 如果表單元素默認type類型保留,去除某位空格或管道符
try { el.type = typeReplace; } catch(e) {}
}
type = typeReplace;
}

if (allpass == false || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
// 需要驗證的有
// input文本框, type, required, pattern, max, min以及自定義個數限制data-min, data-max
// radio, checkbox
// select
// textarea
// 先從特殊的下手,如單複選框
if (type == "radio" && isRequired) {
// 單選框,只需驗證是否必選,同一name單選組只有要一個設置required即可
var eleRadios = el.name? $("input[type='radio'][name='"+ el.name +"']"): $(el)
, radiopass = false;

eleRadios.each(function() {
if (radiopass == false && $(this).is(":checked")) {//20140609 Chvin
radiopass = true;
}
});

if (radiopass == false) {
allpass = remind(eleRadios.get(0), type, tag);
}
} else if (type == "checkbox" && isRequired && !$(el).is(":checked")) {//20140609 zhangxinxu
// 複選框是,只有要required就驗證,木有就不管
allpass = remind(el, type, tag);
} else if (tag == "select" && isRequired && !el.value) {
// 下拉框只要關心值
allpass = remind(el, type, tag);
} else if ((isRequired && self.isEmpty(el)) || !(allpass = self.isRegex(el))) {
// 各種類型文本框以及文本域
// allpass爲true表示是爲空,爲false表示驗證不通過
allpass? remind(el, type, "empty"): remind(el, type, tag);
allpass = false;
} else if (self.isOverflow(el)) {
// 最大值最小值, 個數是否超出的驗證
allpass = false;
}
});

return allpass;
}
};
})();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章