一个写的挺干净的form表单验证,简洁

来源:互联网 发布:期货交易所 数据接口 编辑:程序博客网 时间:2024/05/16 07:38
/*输入框检测js代码用法:<form action = '' onsubmit="return FormValid.valid(this);">*/var FormValid = {valid : function( obj ) {var elements = obj.elements;var length = elements.length;for( var i=0;i<length;i++ ) if( valid = elements[ i ].getAttribute( 'valid' ) ) if( !this.docheck( valid,elements[ i ] ) ) {alert( elements[ i ].getAttribute( 'errmsg' ) );return false;}return true;},Reg : {isQQ : /^[1-9]\d{4,11}$/,isNumber : /^[1-9]\d{1,}/,isZip : /^[1-9]\d{5}$/,isMobile : /^(13|15|18)\d{10}$/,isPhone : /^0\d{2,3}-\d{7,8}$/,isInt : /^[-\+]?\d+$/,isEmail : /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/},docheck : function( valid,node_obj ) {switch( valid ) {case 'isQQ':case 'isNumber':case 'isZip':case 'isMobile':case 'isPhone':case 'isInt':case 'isEmail':var result = this.doReg( valid,node_obj );break;default:var result = eval( 'this.' + valid + '( node_obj );' );break;}if( !result )node_obj.focus();return result;},doReg : function( valid,node_obj ) {var regexp = this.Reg[ valid ] ;var result = regexp.test( node_obj.value );if( !result )node_obj.focus();return result;},required : function( node_obj ) {return node_obj.value != '';},range : function( node_obj ) {return node_obj.value>=node_obj.getAttribute( 'min' ) & node_obj.value<=node_obj.getAttribute( 'max' );},eq : function( node_obj ) {return node_obj.value == node_obj.getAttribute( 'eqValue' );},gt : function( node_obj ) {return node_obj.value >=node_obj.getAttribute( 'gtValue' );}}

0 0