市面上有很多表单验证的框架,教我们怎么验证表单的数据提交,说实话也真的很简单,但是我们会有一种感觉我们要是离开了这些框架的时候,我们有时候
会束手无策,然后js验证写的很不规范,没有一套比较好的模式,那我写这篇的目的就是:我们自己构建js验证应该是什么样子的,来慢慢看一下。
假设我们现在写一个登录的页面(这可能是最简单的数据提交了哦),html页面会有一个用户名和一个密码的文本框让我们用户输入自己的用户名和密码,我们肯定是要判断用户名和密码是否为空,很明显这样的js验证判断是放在onblur事件里面触发,html代码如下:
View Code
<li>
<label for="email">
用户名:
label>
<input name="email" type="text" id="email" maxlength="50" onblur="return ValidateHelper.validateStringValueIsEmpty($(this),'通过','不能为空');" /><em>em>
li>
<li>
<label for="setPwd">
密码:
label>
<input name="setPwd" type="password" id="setPwd" maxlength="16" onblur="return ValidateHelper.validateStringValueIsEmpty($(this),'通过','不能为空');" /><em>em>
li>
ValidateHelper是一个对象,一些验证的方法就是在这个对象里面,我们规定一下,js验证用户的输入有两返回结果,一个成功,一个是失败。成功的时候我们输出成功的提示,
View Code
normalMessage: function(jqueryObj, msg) {
var emObj = $(jqueryObj.parent().find('em')[0]);
emObj.empty().append(msg);
},
warningMessage: function(jqueryObj, msg) {
ValidateHelper.clearMessage(jqueryObj);
var emObj = $(jqueryObj.parent().find('em')[0]);
var spanElement = ""
+ msg
+ "";
emObj.empty().append(spanElement);
},
View Code
clearMessage: function(jqueryObj) {
var emObj = $(jqueryObj.parent().find('em')[0]);
emObj.empty();
},
View Code
validateStringValueIsEmpty: function(obj, normalMsg, warningMsg) {
var jqueryObj = $(obj);
ValidateHelper.clearMessage(obj);
if ($.trim(jqueryObj.val()).length == 0) {
ValidateHelper.warningMessage(jqueryObj, warningMsg);
return false;
}
else {
ValidateHelper.normalMessage(jqueryObj, normalMsg);
return true;
}
},
这个方法会在onblur中被调用的验证方法,里面自然也用到了成功和失败提示方法,以及清除提示的方法。参数有三个,要验证的Dom或者jQuery对象、成功提示信息、失败提示信
View Code
initInfo: function() {
var userName = $('#email');
var userPwd = $('#setPwd');
if (!ValidateHelper.validateStringValueIsEmpty(userName, '通过', '不能为空')) {
userName.focus();
return null;
}
if (!ValidateHelper.validateStringValueIsEmpty(userPwd, '通过', '不能为空')) {
userPwd.focus();
return null;
}
var userInfo = {
UserName: userName.val(),
UserPwd: userPwd.val()
};
return userInfo;
},
post: function() {
var userInfo = ValidateHelper.initInfo();
if (userInfo == null) {
return;
}
$.ajax({
type: "post",
dataType: "text",
url: "Ajax/Module.aspx",
timeout: 30000,
data: { UserName: userInfo.UserName, UserPwd: userInfo.UserPwd },
success: function(data) {
alert(data.toString());
}
});
}
var Validation = {
textCount: function(field, counter, maxLimit) {
var message = $(field).val();
if ($(field).val().length > maxLimit)
$(field).val(message.substring(0, maxLimit))
//$(counter).text(maxLimit-field.value.length);
},
refreshValidator: function(img, input) {
$(img).attr('src', $(img).attr('src') + "&r=" + Math.random());
$(input).focus();
},
isUrl: function(s) {
var strRegex =
/^((http(s)?|ftp|telnet|news|rtsp|mms):\/\/)?(((\w(\-*\w)*\.)+[a-zA-Z]{2,4})|(((1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).){3}(1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).?))(:\d{0,5})?(\/+.*)*$/;
return strRegex.test(s);
},
isDecimal: function(d) { var pattern = /^(([1-9]\d{0,12})|0)(\.\d{1,2})?$/; return pattern.test(d); },
isEmail: function(s) {
var pattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
return pattern.test(s);
},
isLowEmail: function(s) {
var b, e;
b = s.indexOf("@");
e = s.indexOf(".");
if (b <= 0) return false;
if (e < 0 || e == (s.length - 1)) { return false; }
return true;
},
clearNoNum: function(event, obj) {
event = window.event || event;
if (event.keyCode == 37 | event.keyCode == 39) {
return;
}
obj.value = obj.value.replace(/[^\d.]/g, "");
obj.value = obj.value.replace(/^\./g, "");
obj.value = obj.value.replace(/\.{2,}/g, ".");
obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
},
checkNum: function(obj) {
obj.value = obj.value.replace(/\.$/g, "");
},
isInteger: function(value) {
var integerReg = new RegExp(/^\d+$/);
return integerReg.test(value);
},
isValidateReg: function(value) {
var validateReg = /^([A-Za-z0-9\s\-\_\~\!\@\#\$\%\^\&\*\(\)\|\<\>\?\:\;\"\'\.\[\]\{\}\,\+\`\/\\\=]){6,16}$/;
if (validateReg.test(value)) {
return true;
}
return false;
},
isDate: function(strValue) {
var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
if (!objRegExp.test(strValue))
return false;
else {
var arrayDate = strValue.split(RegExp.$1);
var intDay = parseInt(arrayDate[2], 10);
var intYear = parseInt(arrayDate[0], 10);
var intMonth = parseInt(arrayDate[1], 10);
if (intMonth > 12 || intMonth < 1) {
return false;
}
var arrayLookup = { '1': 31, '3': 31, '4': 30, '5': 31, '6': 30, '7': 31,
'8': 31, '9': 30, '10': 31, '11': 30, '12': 31
}
if (arrayLookup[parseInt(arrayDate[1])] != null) {
if (intDay <= arrayLookup[parseInt(arrayDate[1])] && intDay != 0)
return true;
}
if (intMonth - 2 == 0) {
var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
if (((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <= 28)) && intDay != 0)
return true;
}
}
return false;
},
isZip: function(value) {
var validateReg = /^[0-9]{6}$/;
return validateReg.test(value);
},
checkSpecialChar: function(value) {
var validateReg = /([~!@#$%^&*\/\\,.\(\)]){6,16}$/;
return validateReg.test(value);
},
CheckSpecialString: function(value) {
var validateReg = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/;
return validateReg.test(value);
},
isTel: function(s) {
var patrn = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
if (!patrn.exec(s)) return false
return true
},
isMobile: function(value) {
var validateReg = /^1\d{10}$/;
return validateReg.test(value);
},
getLength: function(value) {
return value.replace(/[^\x00-\xff]/g, "**").length;
},
isLicence: function(value) {
var validateReg = /^[A-Za-z]{10}[0-9]{10}$/;
return validateReg.test(value);
},
isPersonalCard: function(value) {
var validateReg = /(^\d{15}$)|(^\d{17}(\d|[A-Za-z]{1})$)/;
return validateReg.test(value);
},
isOrganizationCodeCard: function(value) {
var validateReg = /^[A-Za-z0-9]{9}$/;
return validateReg.test(value);
},
isBankAccount: function(value) {
var validateReg = /^[1-9]{1}[0-9]*$/;
return validateReg.test(value);
},
MaxLength: function(field, maxlimit) {
var j = field.value.replace(/[^\x00-\xff]/g, "**").length;
var tempString = field.value;
var tt = "";
if (j > maxlimit) {
for (var i = 0; i < maxlimit; i++) {
if (tt.replace(/[^\x00-\xff]/g, "**").length < maxlimit)
tt = tempString.substr(0, i + 1);
else
break;
}
if (tt.replace(/[^\x00-\xff]/g, "**").length > maxlimit) {
tt = tt.substr(0, tt.length - 1);
field.value = tt;
}
else {
field.value = tt;
}
}
}
};
validateStringValueForEmail: function(obj, normalMsg, warningMsg) {
var jqueryObj = $(obj);
ValidateHelper.clearMessage(obj);
if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通过", "不能为空")) {
ValidateHelper.warningMessage(jqueryObj, "不能为空");
return false;
}
if (!Validation.isEmail(jqueryObj.val())) {
ValidateHelper.warningMessage(jqueryObj, warningMsg);
return false;
}
else {
ValidateHelper.normalMessage(jqueryObj, normalMsg);
return true;
}
},
validateStringValueForCardID: function(obj, normalMsg, warningMsg) {
var jqueryObj = $(obj);
ValidateHelper.clearMessage(obj);
if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通过", "不能为空")) {
ValidateHelper.warningMessage(jqueryObj, "不能为空");
return false;
}
if (!Validation.isPersonalCard(jqueryObj.val())) {
ValidateHelper.warningMessage(jqueryObj, warningMsg);
return false;
}
else {
ValidateHelper.normalMessage(jqueryObj, normalMsg);
return true;
}
},