Web开发经常要遇到的一个问题就是数据过滤,数据过滤目前大体两道门前台过滤后台过滤,我谈谈个人前台数据过滤走过的过程吧。
在学校的时候从来没想过会过滤数据,测试的时候都是输入的正确的数据,都没考虑过数据过滤这个部分,自己学习的时候走过这些路,我用的JavaScript进行前台数据过滤
第一阶段是每一个页面都写一些function去验证相应的输入框输入的数据长度,格式,必填什么的是否都已经达到要求,这样做JavaScript文件很多,看去很乱,而且有很多输入框都是相同的验证过程,只是输入框的ID不同,并且一次只能验证到一个输入框
第二个阶段是把常用的一些验证都写出通用的方法只要把传入的输入框的ID传进去就OK了,这样做还有不好,还是要去新建JavaScript文件。输入框还是只能验证一个
第三个阶段是在第二个阶段用了一个JavaScript框架jequery
第四个阶段直接在html标记里写标签 比如 datatype=“email”//float,number 等等,在提交服务器之前将全部是数据过来出来,并且是验证全部的输入框。
当然你也可以写一些逻辑判断的在里面,比如验证两次密码相同等 只要在这两个输入框的html中加入相应的标签
在提交服务器是return vali();就可以了,我们需要做的就是在输入框的html中加上标签 和在提交服务器的时候 调用JavaScript函数vali(),我的函数名是这样写的。当然最主要的是如何建造这个JavaScript验证类。网上很多但是看了很复杂,不会改就自己写了一个。和jequery的plug那个差不多。现在把源码贴出,要配合jequery1.32使用,大家给点意见。
代码
/* ----------------------------------------------------------------------
* Description:前台数据过滤 辅助类
*
* Create Author:用二进制做高等数学
*
* Create DateTime:2009.09
*
* Copyright:
*----------------------------------------------------------------------*/
function valid() {
$("input[required=true]:visible,textarea[required=true]:visible").trigger('blur');
var numError = $("form .onError").length;
if (numError) {
return false;
}
return true;
}
function msg(obj, msge) {
var $parent = $(obj).parent();
if ($(obj).attr("msg")) {
$parent.append('<span class="formtips onError">' + $(obj).attr("msg") + '</span>');
}
else {
$parent.append('<span class="formtips onError">' + msge + '</span>');
}
}
$(document).ready(function() {
//必填项后面加上 星号
$("input[required=true]:visible,textarea[required=true]:visible").each(function() {
var $required = $("<strong class='high'>*</strong>");
$(this).parent().append($required);
});
$('input,textarea').blur(function() {
var $parent = $(this).parent();
$parent.find(".formtips").remove();
var val = $.trim(this.value);
var msge = "";
//验证必填项
msge = message['required'];
if ($(this).attr("required")) {
if (null == val || "" == val) {
msg(this, msge);
return;
}
}
//最小长度
msge = message['minlength'] + $(this).attr("minlength") + message['char'];
if ($(this).attr("minlength")) {
if (getLength(val) < $(this).attr("minlength")) {
msg(this, msge);
return;
}
}
//最大长度
msge = message['maxlength'] + $(this).attr("maxlength") + message['char'];
if ($(this).attr("maxlength")) {
if (getLength(val) > $(this).attr("maxlength")) {
msg(this, msge);
return;
}
}
//格式验证
var ischeck = "true";
if ($(this).attr("datatype")) {
if (null == val || "" == val) {
return;
}
var formart = $(this).attr("datatype");
msge = message[formart];
switch (formart) {
case "email":
ischeck = "isEmail('" + val + "')";
break;
case "digital":
ischeck = "isDigital('" + val + "')";
break;
case "date":
ischeck = "isDate('" + val + "')";
break;
case "zipcode":
ischeck = "isZipCode('" + val + "')";
break;
case "pinteger":
ischeck = "isInt('" + val + "')";
break;
case "url":
ischeck = "isUrl('" + val + "')";
break;
case "float":
ischeck = "isFloat('" + val + "')";
break;
case "photo":
ischeck = "isPhoto('" + val + "')";
break;
case "special":
ischeck = "isSpecial('" + val + "')";
break;
case "chinese":
ischeck = "isChinese('" + val + "')";
break;
}
if (!eval(ischeck)) {
msg(this, msge);
return;
}
}
//最大值
msge = message["maxvalue"] + $(this).attr("maxvalue");
if ($(this).attr("maxvalue") && "" != val) {
if (parseFloat(val) > parseFloat($(this).attr("maxvalue"))) {
msg(this, msge);
return;
}
}
//最小值
msge = message["minvalue"] + $(this).attr("minvalue");
if ($(this).attr("minvalue") && "" != val) {
if (parseFloat(val) < parseFloat($(this).attr("minvalue"))) {
msg(this, msge);
return;
}
}
}).keyup(function() {
$(this).triggerHandler("blur");
}).focus(function() {
$(this).triggerHandler("blur");
}); //end blur
//get the length
function getLength(strValue) {
var cArr = strValue.match(/[^\x00-\xff]/ig);
return strValue.length + (cArr == null ? 0 : cArr.length);
}
//validate the email
function isEmail(strEmail) {
if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
return true;
else
return false;
}
//validate the intigral
function isInt(strInt) {
if ("0" == strInt) {
return false;
}
var firstchar = strInt.substring(0, 1);
if ("0" == firstchar && "0" != strInt) {
return false;
}
for (var i = 0; i < strInt.length; i++) {
var ch = strInt.substring(i, i + 1);
if (!("0" <= ch && "9" >= ch)) {
return false;
}
}
return true;
}
//validate the date
function isDate(strDate) {
var datestr = strDate.split('/').join('-');
datestr = datestr.split(':').join('-');
datestr = datestr.split('.').join('-');
if (datestr.split('-')[0].length == 2) {
var current = new Date();
var current_year = current.getFullYear();
datestr = current_year.toString().substring(0, 2) + datestr;
}
var dateFormart = /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/;
var matchArr = datestr.match(dateFormart);
if (null == matchArr) {
return false;
}
month = matchArr[3];
day = matchArr[5];
year = matchArr[1];
if (month < 1 || month > 12) {
return false;
}
if (day < 1 || day > 31) {
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
return false;
}
if (month == 2) {
var isleap = (year / 4 == 0 && (year / 100 != 0 || year / 400 == 0));
if (day > 29) {
return false;
}
if (day == 29 && !isleap) {
return false;
}
}
return true;
}
//validate the zip code
function isZipCode(strZipCode) {
var reg = /^[1-9]\d{5}$/;
return reg.test(strZipCode);
}
//validate the float number
function isFloat(strFloat) {
var tcount = 5; //set the digit of dicimal the number
if (strFloat.substring(0, 1) == ".") {
return false;
}
var pointcount = 0;
for (var i = 0; i < strFloat.length; i++) {
var ch = strFloat.substring(i, i + 1);
if (!((ch >= "0" && ch <= "9") || ch == ".")) {
return false;
}
if (ch == ".") {
pointcount++;
}
if (pointcount > 1) {
return false;
}
}
if (strFloat.indexOf(".") != -1 && strFloat.length - (strFloat.indexOf(".") + 1) > tcount) {
return false;
}
var start1 = strFloat.substring(0, 1);
var start2 = strFloat.substring(1, 2);
if (start1 == 0 && start2 != ".") {
for (var i = 0; i < strFloat.length; i++) {
var ch = strFloat.substring(i, i + 1);
if (ch == 0)
pointcount++;
}
if (pointcount == strFloat.length) {
return true;
}
return false;
}
return true;
}
//validate the photo
function isPhoto(strPhoto) {
var strFormat = "jpg | jpeg | gif | png | bmp | pic ";
if (strPhoto.indexOf(".") > -1) {
var point = strPhoto.lastIndexOf(".");
var file = strPhoto.substring(point + 1, strPhoto.length);
if (!(strFormat.indexOf(file.toLowerCase()) > -1)) {
return false;
}
}
return true;
}
//validate the special character
function isSpecial(strspecial) {
for (var i = 0; i < strspecial.length; i++) {
var ch = strspecial.charAt(i);
if ((ch == "`") || (ch == "~") || (ch == "!") || (ch == "@") ||
(ch == "#") || (ch == "\"") || (ch == "^") || (ch == "&") ||
(ch == "*") || (ch == "(") || (ch == ")") || (ch == "+") ||
(ch == "=") || (ch == "|") || (ch == "{") || (ch == "}") ||
(ch == "[") || (ch == "]") || (ch == ":") || (ch == ";") ||
(ch == "'") || (ch == '"') || (ch == "<") || (ch == ">") ||
(ch == ",") || (ch == ".") || (ch == "\\") || (ch == "?") ||
(ch == "/")) {
return false;
}
}
return true;
}
//validate the number
function isDigital(strValue) {
var reg = /^\d+(?=\.{0,1}\d+$|$)/
return reg.test(strValue)
}
//validate the Url
function isUrl(strValue) {
var reg = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
return strValue.match(reg);
}
//validate the Chinese
function isChinese(strValue) {
if (escape(strValue).indexOf("%u") != -1) {
return false;
}
return true;
}
var message = {
"required": "\u5FC5\u586B\u9879", //必填项
"minlength": "\u6700\u5C0F\u957F\u5EA6", //最小长度
"maxlength": "\u6700\u5927\u957F\u5EA6", //最大长度
"char": "\u5B57\u7B26", //字符
"email": "\u4E3AEmail\u683C\u5F0F", //为Email格式
"digital": "\u4E3A\u6570\u5B57\u683C\u5F0F", //为数字格式
"date": "\u4E3A\u65E5\u671F\u683C\u5F0F", //为日期格式
"zipcode": "\u4E3A\u90AE\u7F16\u683C\u5F0F", //为邮编格式
"pinteger": "\u4E3A\u6B63\u6574\u6570", //为正整数
"url": "\u4E3AUrl\u683C\u5F0F", //为 Url 格式
"float": "\u5C0F\u6570\u4E14\u4FDD\u7559\u4E94\u4F4D", //小数且保留两位
"photo": "\u4E3A\u56FE\u7247\u683C\u5F0F", //为图片格式
"special": "\u542B\u6709\u7279\u6B8A\u5B57\u7B26", //含有特殊字符
"chinese": "\u4E3A\u82F1\u6587\u6216\u82F1\u6587\u548C\u6570\u5B57\u7684\u7EC4\u5408", //为英文或英文和数字的组合
"maxvalue": "\u6700\u5927\u503C\u4E3A", //最大值为
"minvalue": "\u6700\u5C0F\u503C\u70BA"//最小值为
};
})
* Description:前台数据过滤 辅助类
*
* Create Author:用二进制做高等数学
*
* Create DateTime:2009.09
*
* Copyright:
*----------------------------------------------------------------------*/
function valid() {
$("input[required=true]:visible,textarea[required=true]:visible").trigger('blur');
var numError = $("form .onError").length;
if (numError) {
return false;
}
return true;
}
function msg(obj, msge) {
var $parent = $(obj).parent();
if ($(obj).attr("msg")) {
$parent.append('<span class="formtips onError">' + $(obj).attr("msg") + '</span>');
}
else {
$parent.append('<span class="formtips onError">' + msge + '</span>');
}
}
$(document).ready(function() {
//必填项后面加上 星号
$("input[required=true]:visible,textarea[required=true]:visible").each(function() {
var $required = $("<strong class='high'>*</strong>");
$(this).parent().append($required);
});
$('input,textarea').blur(function() {
var $parent = $(this).parent();
$parent.find(".formtips").remove();
var val = $.trim(this.value);
var msge = "";
//验证必填项
msge = message['required'];
if ($(this).attr("required")) {
if (null == val || "" == val) {
msg(this, msge);
return;
}
}
//最小长度
msge = message['minlength'] + $(this).attr("minlength") + message['char'];
if ($(this).attr("minlength")) {
if (getLength(val) < $(this).attr("minlength")) {
msg(this, msge);
return;
}
}
//最大长度
msge = message['maxlength'] + $(this).attr("maxlength") + message['char'];
if ($(this).attr("maxlength")) {
if (getLength(val) > $(this).attr("maxlength")) {
msg(this, msge);
return;
}
}
//格式验证
var ischeck = "true";
if ($(this).attr("datatype")) {
if (null == val || "" == val) {
return;
}
var formart = $(this).attr("datatype");
msge = message[formart];
switch (formart) {
case "email":
ischeck = "isEmail('" + val + "')";
break;
case "digital":
ischeck = "isDigital('" + val + "')";
break;
case "date":
ischeck = "isDate('" + val + "')";
break;
case "zipcode":
ischeck = "isZipCode('" + val + "')";
break;
case "pinteger":
ischeck = "isInt('" + val + "')";
break;
case "url":
ischeck = "isUrl('" + val + "')";
break;
case "float":
ischeck = "isFloat('" + val + "')";
break;
case "photo":
ischeck = "isPhoto('" + val + "')";
break;
case "special":
ischeck = "isSpecial('" + val + "')";
break;
case "chinese":
ischeck = "isChinese('" + val + "')";
break;
}
if (!eval(ischeck)) {
msg(this, msge);
return;
}
}
//最大值
msge = message["maxvalue"] + $(this).attr("maxvalue");
if ($(this).attr("maxvalue") && "" != val) {
if (parseFloat(val) > parseFloat($(this).attr("maxvalue"))) {
msg(this, msge);
return;
}
}
//最小值
msge = message["minvalue"] + $(this).attr("minvalue");
if ($(this).attr("minvalue") && "" != val) {
if (parseFloat(val) < parseFloat($(this).attr("minvalue"))) {
msg(this, msge);
return;
}
}
}).keyup(function() {
$(this).triggerHandler("blur");
}).focus(function() {
$(this).triggerHandler("blur");
}); //end blur
//get the length
function getLength(strValue) {
var cArr = strValue.match(/[^\x00-\xff]/ig);
return strValue.length + (cArr == null ? 0 : cArr.length);
}
//validate the email
function isEmail(strEmail) {
if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
return true;
else
return false;
}
//validate the intigral
function isInt(strInt) {
if ("0" == strInt) {
return false;
}
var firstchar = strInt.substring(0, 1);
if ("0" == firstchar && "0" != strInt) {
return false;
}
for (var i = 0; i < strInt.length; i++) {
var ch = strInt.substring(i, i + 1);
if (!("0" <= ch && "9" >= ch)) {
return false;
}
}
return true;
}
//validate the date
function isDate(strDate) {
var datestr = strDate.split('/').join('-');
datestr = datestr.split(':').join('-');
datestr = datestr.split('.').join('-');
if (datestr.split('-')[0].length == 2) {
var current = new Date();
var current_year = current.getFullYear();
datestr = current_year.toString().substring(0, 2) + datestr;
}
var dateFormart = /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/;
var matchArr = datestr.match(dateFormart);
if (null == matchArr) {
return false;
}
month = matchArr[3];
day = matchArr[5];
year = matchArr[1];
if (month < 1 || month > 12) {
return false;
}
if (day < 1 || day > 31) {
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
return false;
}
if (month == 2) {
var isleap = (year / 4 == 0 && (year / 100 != 0 || year / 400 == 0));
if (day > 29) {
return false;
}
if (day == 29 && !isleap) {
return false;
}
}
return true;
}
//validate the zip code
function isZipCode(strZipCode) {
var reg = /^[1-9]\d{5}$/;
return reg.test(strZipCode);
}
//validate the float number
function isFloat(strFloat) {
var tcount = 5; //set the digit of dicimal the number
if (strFloat.substring(0, 1) == ".") {
return false;
}
var pointcount = 0;
for (var i = 0; i < strFloat.length; i++) {
var ch = strFloat.substring(i, i + 1);
if (!((ch >= "0" && ch <= "9") || ch == ".")) {
return false;
}
if (ch == ".") {
pointcount++;
}
if (pointcount > 1) {
return false;
}
}
if (strFloat.indexOf(".") != -1 && strFloat.length - (strFloat.indexOf(".") + 1) > tcount) {
return false;
}
var start1 = strFloat.substring(0, 1);
var start2 = strFloat.substring(1, 2);
if (start1 == 0 && start2 != ".") {
for (var i = 0; i < strFloat.length; i++) {
var ch = strFloat.substring(i, i + 1);
if (ch == 0)
pointcount++;
}
if (pointcount == strFloat.length) {
return true;
}
return false;
}
return true;
}
//validate the photo
function isPhoto(strPhoto) {
var strFormat = "jpg | jpeg | gif | png | bmp | pic ";
if (strPhoto.indexOf(".") > -1) {
var point = strPhoto.lastIndexOf(".");
var file = strPhoto.substring(point + 1, strPhoto.length);
if (!(strFormat.indexOf(file.toLowerCase()) > -1)) {
return false;
}
}
return true;
}
//validate the special character
function isSpecial(strspecial) {
for (var i = 0; i < strspecial.length; i++) {
var ch = strspecial.charAt(i);
if ((ch == "`") || (ch == "~") || (ch == "!") || (ch == "@") ||
(ch == "#") || (ch == "\"") || (ch == "^") || (ch == "&") ||
(ch == "*") || (ch == "(") || (ch == ")") || (ch == "+") ||
(ch == "=") || (ch == "|") || (ch == "{") || (ch == "}") ||
(ch == "[") || (ch == "]") || (ch == ":") || (ch == ";") ||
(ch == "'") || (ch == '"') || (ch == "<") || (ch == ">") ||
(ch == ",") || (ch == ".") || (ch == "\\") || (ch == "?") ||
(ch == "/")) {
return false;
}
}
return true;
}
//validate the number
function isDigital(strValue) {
var reg = /^\d+(?=\.{0,1}\d+$|$)/
return reg.test(strValue)
}
//validate the Url
function isUrl(strValue) {
var reg = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
return strValue.match(reg);
}
//validate the Chinese
function isChinese(strValue) {
if (escape(strValue).indexOf("%u") != -1) {
return false;
}
return true;
}
var message = {
"required": "\u5FC5\u586B\u9879", //必填项
"minlength": "\u6700\u5C0F\u957F\u5EA6", //最小长度
"maxlength": "\u6700\u5927\u957F\u5EA6", //最大长度
"char": "\u5B57\u7B26", //字符
"email": "\u4E3AEmail\u683C\u5F0F", //为Email格式
"digital": "\u4E3A\u6570\u5B57\u683C\u5F0F", //为数字格式
"date": "\u4E3A\u65E5\u671F\u683C\u5F0F", //为日期格式
"zipcode": "\u4E3A\u90AE\u7F16\u683C\u5F0F", //为邮编格式
"pinteger": "\u4E3A\u6B63\u6574\u6570", //为正整数
"url": "\u4E3AUrl\u683C\u5F0F", //为 Url 格式
"float": "\u5C0F\u6570\u4E14\u4FDD\u7559\u4E94\u4F4D", //小数且保留两位
"photo": "\u4E3A\u56FE\u7247\u683C\u5F0F", //为图片格式
"special": "\u542B\u6709\u7279\u6B8A\u5B57\u7B26", //含有特殊字符
"chinese": "\u4E3A\u82F1\u6587\u6216\u82F1\u6587\u548C\u6570\u5B57\u7684\u7EC4\u5408", //为英文或英文和数字的组合
"maxvalue": "\u6700\u5927\u503C\u4E3A", //最大值为
"minvalue": "\u6700\u5C0F\u503C\u70BA"//最小值为
};
})