• 代码段:js表单提交检测


      市面上当然有很多成型的框架,比如jquery的validation插件各种吧。现在工作地,由于前端童鞋也没用这些个插件。根据业务的要求,自己就在代码里写了个简单的表单提交的检测代码(php的也写了一个哈哈),类也封装的不太完善,很多校验规则也没做,类里边对传入参数也没做啥改动,算是不健壮吧(主要自己不会坑自己,老实的该传什么就传什么了哈哈)。业务上主要就是对表单字段的必填啊,类型啊,长度这些个限制。

     
    	<script type="text/javascript" src="jquery.js"></script>
    	<script type="text/javascript">
    		  
    		function Submit_check(obj){
    			this.obj = obj;
    			this.str = '';
    			this.arr = {
    				'empty_arr':[[], '不能为空'], // 元素为空数组
    				'type_arr':[[], '类型不正确'], // 元素类型不正确
    				'length_arr':[[], '字符过长'] // 元素过长
    			};
    			this.alert_str = function(){
    				// 遍历满足情况
    				for(var x in this.obj){
    					var name = this.obj[x][0];// 表单字段的中文名
    					var value = this.obj[x][1];// 字段的值
    					// 为空
    					if (typeof value == 'undefined' || value == '' ){
    						this.arr.empty_arr[0].push(name);
    					} else {
    						// 类型错误
    						if (this.obj[x][3] !='' && this.obj[x][3] != typeof value) this.arr.type_arr[0].push(name);
    						// 长度过长
    						if (this.obj[x][2] !=0 && this.obj[x][2] < value.length) this.arr.length_arr[0].push(name);
    					}
    				}
    				// 输出str
    				for(var y in this.arr){
    					if (this.arr[y][0].length){
    						this.str += this.arr[y][0].join(',')+' '+this.arr[y][1]+'
    ';
    					}
    				}
    				return this.str;
    			}
    		}
    
    		var a1 = 'b',
    		   b1 = 12,
    		   c1 = 'aaadsfaaaaaab',
    		   d1 = 'a',
    		   e1 = '';
    
    		// key->表单字段英文名    value内数组顺序-->字段中文名、值、长度、类型;
    		// 长度为0表示不需要检测长度;类型为空表示不需要检测类型
    		var obj = {
    			'a' : ['地球', a1, 10, 'number'],
    			'b' : ['火星', b1, 0, 'number'],
    			'c' : ['月球', c1, 8, ''],
    			'd' : ['土星', d1, 12, 'string'],
    			'e' : ['木星', e1, 8, '']
    		};
    var str = new Submit_check(obj).alert_str(); if (str){ alert(str); } </script>

      

  • 相关阅读:
    确定比赛名次
    What Are You Talking About
    小兔的棋盘
    How Many Answers Are Wrong
    备份当前的ubuntu系统生成iso
    eclipse导入maven项目有时出现web.xml is missing的问题
    eclipse自动添加版权信息
    javac不是内部或外部命令
    linux目录权限
    python import error:no module named yaml
  • 原文地址:https://www.cnblogs.com/firstForEver/p/4933922.html
Copyright © 2020-2023  润新知