阅读(101)
赞(0)
js常用工具大全
2016-08-10 17:33:54 更新
Date工具类
/********************** date工具类 ***************/
Date.prototype.format = function(format){
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
return format;
};
公共工具类
对输入框里内容清空,对textarea,可以直接$("textarea").empty();如果使用$("textarea").html("");也可能会造成浏览器内存溢出。
/********************** 公共工具类 ***************/
var PublicUtil ={
isNotEmpty: function(val){
return !this.isEmpty(val);
},
isEmpty: function(val){
if ((val==null || typeof(val)=="undefined")|| (typeof(val)=="string"&&val==""&&val!="undefined")){
return true;
}else{
return false;
}
},
isDebug: function(){
if(this.isNotEmpty(configDebug)&&configDebug=="true"){
return true;
}else{
return false;
}
},
//去除元素内所有内容 strIds:"#id1,#id2,#id3"
emptyHtml: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).html("");
});
}else{
obj.html("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyHtml(strIds)】,error!");
}
}
},
//去除元素的值 strIds:"#id1,#id2,#id3"
emptyValue: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).val("");
});
}else{
obj.val("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyValue(strIds)】,error!");
}
}
},
//去除Textarea内所有内容 strIds:"#id1,#id2,#id3"
emptyTextarea: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).empty();
$(this).val("");
});
}else{
obj.empty();
obj.val("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyTextarea(strIds)】,error!");
}
}
}
}
String工具类
字符串的拼接一定使用StringBuffer来拼接,否则容易造成浏览器卡顿或内存溢出。特别是针对一些执行js效率不高的浏览器!!
/********************** String工具类***************/
//trim去掉字符串两边的指定字符,默去空格
String.prototype.trim = function(tag) {
if (!tag) {
tag = '\\s';
}else {
if (tag == '\\') {
tag = '\\\\';
} else if (tag == ',' || tag == '|' || tag == ';') {
tag = '\\' + tag;
}else {
tag = '\\s';
}
}
eval('var reg=/(^' + tag + '+)|(' + tag + '+$)/g;');
return this.replace(reg, '');
};
//字符串截取后面加入...
String.prototype.interceptString = function(len) {
if (this.length > len) {
return this.substring(0, len) + "...";
} else {
return this;
}
}
//将一个字符串用给定的字符变成数组
String.prototype.toArray = function(tag) {
if (this.indexOf(tag) != -1) {
return this.split(tag);
}else {
if (this != '') {
return [this.toString()];
}else {
return [];
}
}
}
//只留下数字(0123456789)
String.prototype.toNumber= function() {
return this.replace(/\D/g, "");
}
//保留中文
String.prototype.toCN= function() {
var regEx = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g;
return this.replace(regEx, '');
}
//转成int
String.prototype.toInt= function() {
var temp = this.replace(/\D/g, "");
return isNaN(parseInt(temp)) ? this.toString() : parseInt(temp);
}
//是否是以XX开头
String.prototype.startsWith= function(tag){
return this.substring(0, tag.length) == tag;
}
//是否已XX结尾
String.prototype.endWith= function(tag){
return this.substring(this.length - tag.length) == tag;
}
//StringBuffer
var StringBuffer = function() {
this._strs = new Array;
};
StringBuffer.prototype.append = function (str) {
this._strs.push(str);
};
StringBuffer.prototype.toString = function() {
return this._strs.join("");
};
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
Array工具类
/********************** Arry ***************/
//根据数据取得再数组中的索引
Array.prototype.getIndex = function(obj){
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
return i;
}
}
return -1;
}
//移除数组中的某元素
Array.prototype.remove= function (obj) {
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
this.splice(i, 1);
break;
}
}
return this;
}
//判断元素是否在数组中
Array.prototype.contains= function (obj) {
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
return true;
}
}
return false;
}
浏览器相关操作
/********************** 浏览器相关操作 ***************/
//进入全屏模式, 判断各种浏览器,找到正确的方法
var launchFullScreen = function (element) {
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
return true;
}
//退出全屏模式
var exitFullScreen = function () {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
return false;
}
//cookie操作
var CookieUtil={
path: "/",
domain: 'demo.j2ee.com',
add: function(name,val){
$.cookie(name, val, {expires: 7, path: this.path, domain: this.domain, secure: true});
},
remove: function(name){
$.cookie(name, null,{path: this.path, domain: this.domain});
},
get: function(name){
$.cookie(name,{path: this.path, domain: this.domain});
}
}
//error
var error={
e_404: function(){
alertMessage("404","未找到改页面!","warning");
},
e_500: function(){
alertMessage("500","服务器内部错误!","error");
},
e_403: function(){
alertMessage("403","权限不足!","warning");
}
}
层拖动对象类
原理:
需拖动的层包括两类对象,主移动区域,鼠标拖动事件区域(可与主移动区域一致),鼠标在事件区域按下时为其注册鼠标移动及鼠标释放事件,非IE浏览器需为document注册事件,同时为其设置捕获事件(关键事件setCapture),鼠标移动时重置主区域Style中的位置属性(left,top),释放鼠标后移除事件绑定。
$.extend({
ObjMove: function (op) {
var settings = $.extend({
containerId: 'divPopWindow', //容器编号
dragIds: ['divPopWindowDragTop', 'divPopWindowDragBottom'], //拖动层编号集
onMouseDownEvent: null, //鼠标按下时执行的附加事件
onMouseMoveEvent: null, //鼠标移动时执行的附加事件
onMouseUpEvent: null //鼠标释放时执行的附加事件
}, op || {});
var containerObj = null;
var left = 0;
var top = 0;
init();
function init() {
containerObj = document.getElementById(settings.containerId);
containerObj.style.position = 'absolute';
$(settings.dragIds).each(function () {
$('#' + this).bind('mousedown', function (ev) {
onMouseDown(this, ev);
});
});
}
//鼠标左键事件
function onMouseDown(o, ev) {
var event = window.event || ev;
if (o.setCapture){
o.setCapture();
//IE下事件绑定
$(o).bind('mousemove', function(ev){
onMouseMove(ev);
});
$(o).bind('mouseup', function(o){
onMouseUp(this);
});
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件绑定
document.addEventListener('mousemove', onMouseMove, true);
document.addEventListener('mouseup', onMouseUp, true);
}
//计算弹出层的相对初始位置
left = event.clientX - containerObj.offsetLeft;
top = event.clientY - containerObj.offsetTop;
if(settings.onMouseDownEvent != null){
settings.onMouseDownEvent();
}
}
//鼠标移动事件
function onMouseMove(ev){
var event = window.event || ev;
if(!event.pageX){
event.pageX = event.clientX;
}
if(!event.pageY){
event.pageY = event.clientY;
}
containerObj.style.left = (event.pageX - left) + 'px';
containerObj.style.top = (event.pageY - top) + 'px';
if(settings.onMouseMoveEvent != null){
settings.onMouseMoveEvent();
}
}
//鼠标左键释放事件
function onMouseUp(o){
if (o.releaseCapture){
o.releaseCapture();
//IE下事件释放
$(o).unbind('mousemove');
$(o).unbind('mouseup');
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件释放
document.removeEventListener("mousemove", onMouseMove, true);
document.removeEventListener("mouseup", onMouseUp, true);
}
if(settings.onMouseUpEvent != null){
settings.onMouseUpEvent();
}
}
}
})
示例:
<div id="divPopWindow" style="width: 200px; height: 200px;">
<div id="divDragTop" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
<div style="width: 100%; height: 152px; background-color: black;"></div>
<div id="divDragBottom" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
</div>
<script type="text/javascript">
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divDragTop', 'divDragBottom']
});
</script>
弹出窗口
$.extend({
OpenWindow: function (op) {
var settings = $.extend({
title: '提示', //弹出窗口标题
content: '', //弹出窗口内容:内容或URL地址
contentType: 'frame', //弹出窗口内容区类型:frame或文本
width: 300, //宽度
height: 300 //高度
}, op || {});
var windowObj = null; //主窗口
var dragTopObj = null; //拖动对象
var shadowObj = null; //阴影对象
var normalColor = '#336699';
var activeColor = 'orange';
init();
function init() {
windowObj = $('#divPopWindow');
if(windowObj.length == 0){
var content = '';
if(settings.contentType == 'frame') {
content = '<iframe id="divPopWindowFrame" name="divPopWindowFrame" style="width: 100%; height: ' + (settings.height - 20 - 4) + 'px;" frameborder="0px" scrolling="scrolling" src="' + settings.content + '"></iframe>';
} else {
content = settings.content;
}
var fixW = 8; //宽度修正值
if(!$.browser.msie){
fixW = 12;
}
var windowHtml = '<div id="divPopWindow" style="z-index: 1000; width: ' + settings.width + 'px; height: ' + settings.height + 'px; '
+ 'background-color: ' + normalColor + '; color: ' + normalColor + '; font-size: 8pt; font-family: Tahoma; position: absolute; cursor: move; border: 2px solid ' + normalColor + ';">'
+ ' <div id="divPopWindowDragTop" style="background-color: ' + normalColor + '; width: ' + (settings.width - (2 * 2)) + 'px; height: 20px; color: white;" ondblclick="">'
+ ' <span style="float: left; display:block; width: ' + (settings.width - (2 * 12) - 4 - fixW) + 'px; margin-left: 5px; margin-top: 3px">' + settings.title + '</span>'
+ ' <span id="spPopWindowMin" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">0</span>'
+ ' <span id="spPopWindowClose" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">r</span>'
+ ' </div>'
+ ' <div id="divPopWindowContent" style="width: 100%; height: ' + (settings.height - 20) + 'px; background-color: white; line-height: 14px; word-break: break-all;">'
+ ' <div id="divPopWindowContentBox" style="width: 100%; height: ' + (settings.height - 20) + 'px; overflow: auto;">'
+ ' </div>'
+ ' </div>'
+ "</div>"
+ '<div id="divPopWindowShadow" style="display: none; width: ' + settings.width + 'px; height:' + settings.height + 'px; top: 0px; left: 0px; '
+ 'z-index: 999; position: absolute; background-color: black; filter:alpha(opacity=40);">'
+ '</div>';
$(windowHtml).appendTo('body');
$('#spPopWindowMin').bind('click', switchContentArea);
$('#spPopWindowClose').bind('click', close);
}
windowObj = $('#divPopWindow');
dragTopObj = $('#divPopWindowDragTop');
shadowObj = $('#divPopWindowShadow');
$('#divPopWindowContentBox').html(content);
/*初始化窗口容器位置*/
var left = (document.body.clientWidth - settings.width) / 2;
var top = document.documentElement.clientHeight;
var topscroll = document.body.clientHeight;
if (topscroll > top) {
top = topscroll;
}
top = (top - settings.height) / 2;
if (top < 20) {
top = 20;
}
windowObj[0].style.left = left + 'px';
windowObj[0].style.top = top + 'px';
windowObj.show();
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divPopWindowDragTop'],
onMouseDownEvent: onMouseDown,
onMouseMoveEvent: onMouseMove,
onMouseUpEvent: onMouseUp
});
}
//鼠标按下时执行的事件
function onMouseDown(){
windowObj.css({ backgroundColor: activeColor, borderColor: activeColor});
dragTopObj.css({ backgroundColor: activeColor});
shadowObj.show();
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠标移动时执行的事件
function onMouseMove(){
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠标释放时执行的事件
function onMouseUp(){
windowObj.css({ backgroundColor: normalColor, borderColor: normalColor});
dragTopObj.css({ backgroundColor: normalColor});
shadowObj.hide();
}
//切换内容显示区
function switchContentArea(){
if($('#divPopWindowContent').css('display') != 'none'){
$('#divPopWindowContent').hide();
$('#spPopWindowMin').html('2')
windowObj.height(24);
shadowObj.height(24);
}else{
$('#divPopWindowContent').show();
$('#spPopWindowMin').html('0')
windowObj.height(settings.height);
shadowObj.height(settings.height);
}
}
//关闭窗口
function close(){
windowObj.unbind().hide();
dragTopObj.unbind();
$('#divPopWindowFrame').attr('src', '');
}
}
})
调用:
$.OpenWindow({
content: 'window.html'
});
表单验证工具类
需拖动的层包括两类对象,主移动区域,鼠标拖动事件区域(可与主移动区域一致),鼠标在事件区域按下时为其注册鼠标移动及鼠标释放事件,非IE浏览器需为document注册事件,同时为其设置捕获事件(关键事件setCapture),鼠标移动时重置主区域Style中的位置属性(left,top),释放鼠标后移除事件绑定。
$.extend({
ObjMove: function (op) {
var settings = $.extend({
containerId: 'divPopWindow', //容器编号
dragIds: ['divPopWindowDragTop', 'divPopWindowDragBottom'], //拖动层编号集
onMouseDownEvent: null, //鼠标按下时执行的附加事件
onMouseMoveEvent: null, //鼠标移动时执行的附加事件
onMouseUpEvent: null //鼠标释放时执行的附加事件
}, op || {});
var containerObj = null;
var left = 0;
var top = 0;
init();
function init() {
containerObj = document.getElementById(settings.containerId);
containerObj.style.position = 'absolute';
$(settings.dragIds).each(function () {
$('#' + this).bind('mousedown', function (ev) {
onMouseDown(this, ev);
});
});
}
//鼠标左键事件
function onMouseDown(o, ev) {
var event = window.event || ev;
if (o.setCapture){
o.setCapture();
//IE下事件绑定
$(o).bind('mousemove', function(ev){
onMouseMove(ev);
});
$(o).bind('mouseup', function(o){
onMouseUp(this);
});
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件绑定
document.addEventListener('mousemove', onMouseMove, true);
document.addEventListener('mouseup', onMouseUp, true);
}
//计算弹出层的相对初始位置
left = event.clientX - containerObj.offsetLeft;
top = event.clientY - containerObj.offsetTop;
if(settings.onMouseDownEvent != null){
settings.onMouseDownEvent();
}
}
//鼠标移动事件
function onMouseMove(ev){
var event = window.event || ev;
if(!event.pageX){
event.pageX = event.clientX;
}
if(!event.pageY){
event.pageY = event.clientY;
}
containerObj.style.left = (event.pageX - left) + 'px';
containerObj.style.top = (event.pageY - top) + 'px';
if(settings.onMouseMoveEvent != null){
settings.onMouseMoveEvent();
}
}
//鼠标左键释放事件
function onMouseUp(o){
if (o.releaseCapture){
o.releaseCapture();
//IE下事件释放
$(o).unbind('mousemove');
$(o).unbind('mouseup');
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件释放
document.removeEventListener("mousemove", onMouseMove, true);
document.removeEventListener("mouseup", onMouseUp, true);
}
if(settings.onMouseUpEvent != null){
settings.onMouseUpEvent();
}
}
}
})
示例:
<div id="divPopWindow" style="width: 200px; height: 200px;">
<div id="divDragTop" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
<div style="width: 100%; height: 152px; background-color: black;"></div>
<div id="divDragBottom" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
</div>
<script type="text/javascript">
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divDragTop', 'divDragBottom']
});
</script>
弹出窗口
$.extend({
OpenWindow: function (op) {
var settings = $.extend({
title: '提示', //弹出窗口标题
content: '', //弹出窗口内容:内容或URL地址
contentType: 'frame', //弹出窗口内容区类型:frame或文本
width: 300, //宽度
height: 300 //高度
}, op || {});
var windowObj = null; //主窗口
var dragTopObj = null; //拖动对象
var shadowObj = null; //阴影对象
var normalColor = '#336699';
var activeColor = 'orange';
init();
function init() {
windowObj = $('#divPopWindow');
if(windowObj.length == 0){
var content = '';
if(settings.contentType == 'frame') {
content = '<iframe id="divPopWindowFrame" name="divPopWindowFrame" style="width: 100%; height: ' + (settings.height - 20 - 4) + 'px;" frameborder="0px" scrolling="scrolling" src="' + settings.content + '"></iframe>';
} else {
content = settings.content;
}
var fixW = 8; //宽度修正值
if(!$.browser.msie){
fixW = 12;
}
var windowHtml = '<div id="divPopWindow" style="z-index: 1000; width: ' + settings.width + 'px; height: ' + settings.height + 'px; '
+ 'background-color: ' + normalColor + '; color: ' + normalColor + '; font-size: 8pt; font-family: Tahoma; position: absolute; cursor: move; border: 2px solid ' + normalColor + ';">'
+ ' <div id="divPopWindowDragTop" style="background-color: ' + normalColor + '; width: ' + (settings.width - (2 * 2)) + 'px; height: 20px; color: white;" ondblclick="">'
+ ' <span style="float: left; display:block; width: ' + (settings.width - (2 * 12) - 4 - fixW) + 'px; margin-left: 5px; margin-top: 3px">' + settings.title + '</span>'
+ ' <span id="spPopWindowMin" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">0</span>'
+ ' <span id="spPopWindowClose" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">r</span>'
+ ' </div>'
+ ' <div id="divPopWindowContent" style="width: 100%; height: ' + (settings.height - 20) + 'px; background-color: white; line-height: 14px; word-break: break-all;">'
+ ' <div id="divPopWindowContentBox" style="width: 100%; height: ' + (settings.height - 20) + 'px; overflow: auto;">'
+ ' </div>'
+ ' </div>'
+ "</div>"
+ '<div id="divPopWindowShadow" style="display: none; width: ' + settings.width + 'px; height:' + settings.height + 'px; top: 0px; left: 0px; '
+ 'z-index: 999; position: absolute; background-color: black; filter:alpha(opacity=40);">'
+ '</div>';
$(windowHtml).appendTo('body');
$('#spPopWindowMin').bind('click', switchContentArea);
$('#spPopWindowClose').bind('click', close);
}
windowObj = $('#divPopWindow');
dragTopObj = $('#divPopWindowDragTop');
shadowObj = $('#divPopWindowShadow');
$('#divPopWindowContentBox').html(content);
/*初始化窗口容器位置*/
var left = (document.body.clientWidth - settings.width) / 2;
var top = document.documentElement.clientHeight;
var topscroll = document.body.clientHeight;
if (topscroll > top) {
top = topscroll;
}
top = (top - settings.height) / 2;
if (top < 20) {
top = 20;
}
windowObj[0].style.left = left + 'px';
windowObj[0].style.top = top + 'px';
windowObj.show();
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divPopWindowDragTop'],
onMouseDownEvent: onMouseDown,
onMouseMoveEvent: onMouseMove,
onMouseUpEvent: onMouseUp
});
}
//鼠标按下时执行的事件
function onMouseDown(){
windowObj.css({ backgroundColor: activeColor, borderColor: activeColor});
dragTopObj.css({ backgroundColor: activeColor});
shadowObj.show();
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠标移动时执行的事件
function onMouseMove(){
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠标释放时执行的事件
function onMouseUp(){
windowObj.css({ backgroundColor: normalColor, borderColor: normalColor});
dragTopObj.css({ backgroundColor: normalColor});
shadowObj.hide();
}
//切换内容显示区
function switchContentArea(){
if($('#divPopWindowContent').css('display') != 'none'){
$('#divPopWindowContent').hide();
$('#spPopWindowMin').html('2')
windowObj.height(24);
shadowObj.height(24);
}else{
$('#divPopWindowContent').show();
$('#spPopWindowMin').html('0')
windowObj.height(settings.height);
shadowObj.height(settings.height);
}
}
//关闭窗口
function close(){
windowObj.unbind().hide();
dragTopObj.unbind();
$('#divPopWindowFrame').attr('src', '');
}
}
})
调用:
$.OpenWindow({
content: 'window.html'
});
表单验证工具类
原理:
利用控件自定义属性绑定验证类型、提示说明,验证时通过验证类型调用验证方法,返回真假值:
function ValidObj(op) {
var obj = new Object;
obj.Valid = valid;
var settings = $.extend({
containerId: 'tbInfo' //容器编号
}, op);
function valid() {
var isSuccess = 1;
var inputObj = null;
var types = '';
var msgs = '';
$('#' + settings.containerId).find('[valid]').each(function () {
inputObj = $(this);
types = $(eval($(this).attr('valid')));
msgs = $(eval($(this).attr('msg')));
$(eval($(this).attr('valid'))).each(function(n){
isSuccess = run(inputObj, this.toLowerCase());
if(isSuccess == -1){
alert('系统错误,验证类型不存在,请联系开发人员!');
return false;
}
if(isSuccess == 0){
alert(msgs[n]);
inputObj.focus();
return false;
}
});
if(isSuccess != 1){
return false;
}
});
return isSuccess == 1;
}
//运行表单验证,返回值:-1 验证类型不存在,0 验证失败,1 验证成功
function run(o, type) {
var pattern = null;
var val = o.val();
switch (type) {
case 'null':
//为空验证
if ($.trim(val).length == 0) {
return 0;
}
return 1;
case 'numeric':
//数值验证
pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
break;
case 'notchinese':
//不能包含中文验证
pattern = /^[u4E00-u9FA5]+$/;
break;
case 'email':
//邮箱验证
pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
break;
}
if (pattern == null) {
//未找到验证类型
return -1;
}
if (!pattern.test(val)) {
return 0;
}
return 1;
}
return obj;
}
调用:
<table id="tbTest" cellspacing="1" cellpadding="0" style="background-color: black; width: 100%;">
<tr>
<td>非空及数值验证</td>
<td><input name="tbNotNullAndNumeric" value="" size="20" valid="['null', 'numeric']" msg="['不能为空,请输出', '必须为数值类型,请重新输入']"></td>
</tr>
<tr>
<td>邮件验证</td>
<td><input name="tbEmail" value="" size="20" valid="['email']" msg="['邮件格式不正确,请重新输入']"></td>
</tr>
<tr>
<td colspan="2"><input type="button" onclick="Valid();" value="验证输入框" /></td>
</tr>
</table>
<script type="text/javascript">
function Valid(){
var obj = new ValidObj({
containerId: 'tbTest' //容器编号
});
if(obj.Valid()){
alert('验证成功。');
}
}
</script>
利用控件自定义属性绑定验证类型、提示说明,验证时通过验证类型调用验证方法,返回真假值:
function ValidObj(op) {
var obj = new Object;
obj.Valid = valid;
var settings = $.extend({
containerId: 'tbInfo' //容器编号
}, op);
function valid() {
var isSuccess = 1;
var inputObj = null;
var types = '';
var msgs = '';
$('#' + settings.containerId).find('[valid]').each(function () {
inputObj = $(this);
types = $(eval($(this).attr('valid')));
msgs = $(eval($(this).attr('msg')));
$(eval($(this).attr('valid'))).each(function(n){
isSuccess = run(inputObj, this.toLowerCase());
if(isSuccess == -1){
alert('系统错误,验证类型不存在,请联系开发人员!');
return false;
}
if(isSuccess == 0){
alert(msgs[n]);
inputObj.focus();
return false;
}
});
if(isSuccess != 1){
return false;
}
});
return isSuccess == 1;
}
//运行表单验证,返回值:-1 验证类型不存在,0 验证失败,1 验证成功
function run(o, type) {
var pattern = null;
var val = o.val();
switch (type) {
case 'null':
//为空验证
if ($.trim(val).length == 0) {
return 0;
}
return 1;
case 'numeric':
//数值验证
pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
break;
case 'notchinese':
//不能包含中文验证
pattern = /^[u4E00-u9FA5]+$/;
break;
case 'email':
//邮箱验证
pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
break;
}
if (pattern == null) {
//未找到验证类型
return -1;
}
if (!pattern.test(val)) {
return 0;
}
return 1;
}
return obj;
}
调用:
<table id="tbTest" cellspacing="1" cellpadding="0" style="background-color: black; width: 100%;">
<tr>
<td>非空及数值验证</td>
<td><input name="tbNotNullAndNumeric" value="" size="20" valid="['null', 'numeric']" msg="['不能为空,请输出', '必须为数值类型,请重新输入']"></td>
</tr>
<tr>
<td>邮件验证</td>
<td><input name="tbEmail" value="" size="20" valid="['email']" msg="['邮件格式不正确,请重新输入']"></td>
</tr>
<tr>
<td colspan="2"><input type="button" onclick="Valid();" value="验证输入框" /></td>
</tr>
</table>
<script type="text/javascript">
function Valid(){
var obj = new ValidObj({
containerId: 'tbTest' //容器编号
});
if(obj.Valid()){
alert('验证成功。');
}
}
</script>
← js跳转代码