一个简单的后端验证框架 - firechou的博客

发表时间:2019-02-15 16:59:44
摘要信息

2.后端验证框架有hibernate validate,可以满足大部分的验证功能。但是该验证框架不能指定顺序单独返回错误信息,例如在一个接口调用中,我想实现指定参数顺序单个返回验证...

1.前端验证框架用jquery validate即可满足;

2.后端验证框架有hibernate validate,可以满足大部分的验证功能。但是该验证框架不能指定顺序单独返回错误信息,例如在一个接口调用中,我想实现指定参数顺序单个返回验证提示信息。如是自己写了一个简单的验证框架实现了此功能;

3.该框架的校验思想参考了jqueryvalidate;


package com.impay.pushua.bean.base;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class ValidateUtils {
	/**
	 * @param fields
	 * @param params
	 * @return
	 * 不存在的校验规则:返回true
	 * 关键字不按要求写:返回true
	 * 总之,想要起到校验效果,必须按要求配置。
	 */
	public static SKResult validate(ValidField[] fields, Map<String, String> params){
		
		try {
			for(ValidField field : fields){
				String name = field.getName();
				String desc = field.getDes();
				boolean isValid = field.isValid();
				String[] rules = field.getRules();
				String value = params.get(name); // 对应请求参数值
				if(!isValid){
					return new SKResult(true, "");
				}
				for(String rule : rules){
					String[] arr = rule.replaceAll(" ", "").split(":");
					String arr1 = arr[0]; // required
					String arr2 = arr[1]; // true
					switch (arr1) {
					case "required": // 必须项 required:true|false
						if(Boolean.parseBoolean(arr2)){
							if(value==null || value.trim().length()==0){
								return new SKResult(false, desc+"不能为空");
							}
						}
						break;
					case "number": // 必须输入合法的数字(负数,小数) number:true|false
						if(Boolean.parseBoolean(arr2)){
							try{
								Double.valueOf(value);
							}catch(Exception e){
								return new SKResult(false, desc+"数值类型不合法");
							}
						}
						break;
					case "digits": // 必须输入整数(正负) digits:true|false
						if(Boolean.parseBoolean(arr2)){
							try{
								Integer.valueOf(value);
							}catch(Exception e){
								return new SKResult(false, desc+"数值类型不合法");
							}
						}
						break;
					case "equalTo": // 指定参数值相等 equalTo:#username
						if(!value.equals(params.get(arr2.replace("#","")))){
							return new SKResult(false, name+"与"+arr2.replace("#","")+"值不等");
						}
						break;
					case "maxlength": // 最大长度 maxlength:3
						int maxlength = Integer.parseInt(arr2);
						if(params.get(name).trim().length()>maxlength){
							return new SKResult(false, desc+"最大长度为"+maxlength);
						}
						break;
					case "minlength": // 最小长度 minlength:3
						int minlength = Integer.parseInt(arr2);
						if(params.get(name).trim().length()<minlength){
							return new SKResult(false, desc+"最小长度为"+minlength);
						}
						break;
					case "rangelength": // 输入长度必须介于 5 和 10 之间的字符串(汉字算一个字符)rangelength:[5,10]
						String[] lens = arr2.substring(1, arr2.length()-1).split(",");
						int minLen = Integer.parseInt(lens[0]);
						int maxLen = Integer.parseInt(lens[1]);
						if(value.length()<minLen||value.length()>maxLen){
							return new SKResult(false, desc+"长度应介于"+arr2+"之间");
						}
						break;
					case "range": // 输入值必须介于 5 和 10 之间 range:[5,10]
						try{
							Double.valueOf(value);
						}catch(Exception e){
							return new SKResult(false, desc+"值不合法");
						}
						String[] lens2 = arr2.substring(1, arr2.length()-1).split(",");
						int minValue = Integer.parseInt(lens2[0]);
						int maxValue = Integer.parseInt(lens2[1]);
						if(Double.valueOf(value)<minValue||Double.valueOf(value)>maxValue){
							return new SKResult(false, desc+"值应介于"+arr2+"之间");
						}
						break;
					case "min": // 输入值不能小于 5 min:5
						try{
							Double.valueOf(value);
						}catch(Exception e){
							return new SKResult(false, desc+"值不合法");
						}
						if(Double.parseDouble(value)<Double.parseDouble(arr2)){
							return new SKResult(false, desc+"值不能小于"+arr2);
						}
						break;
					case "max": // 输入值不能大于 5 max:5
						try{
							Double.valueOf(value);
						}catch(Exception e){
							return new SKResult(false, desc+"值不合法");
						}
						if(Double.parseDouble(value)>Double.parseDouble(arr2)){
							return new SKResult(false, desc+"值不能大于"+arr2);
						}
						break;
					case "accept": // 输入拥有合法后缀名的字符串(上传文件的后缀)
						
						break;
					case "isTel":
						String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
						if(!Pattern.matches(regex, value)){
							return new SKResult(false, desc+"格式错误");
						}
						break;
					default:
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("===ValidField格式不合法,请注意检查!");
			return new SKResult(true, "ValidField格式不合法");
		}
		return new SKResult(true, "校验通过");
	}
	
	public static void main(String[] args) {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "18702764599");
		params.put("password", "123");
		ValidField[] fields = {
				new ValidField("username", "手机号", true, new String[]{
					"required:true",
					"isTel:true"
//					"number:true"
//					"digits:true"
//					"maxlength:5"
//					"minlength:11"
//					"rangelength:[ 5 , 10  ]"
//					"range:[5,10]"
//					"min:5"
//					"max:5"
				}),
				/*new ValidField("password", "密码", true, new String[]{
//					"required:true",
					"isPassword:true",
//					"equalTo:#username"
					"max:2"
				})*/
		};
		
		SKResult sk = ValidateUtils.validate(fields, params);
		System.out.println(sk);
		/**
		 * output
		 * SKResult [result=true, respMsg=校验通过, obj=null, type=null]
		 */
	}
}

package com.impay.pushua.bean.base;


/**
 * 提现请求
 * 
 * @author huwj
 * 
 */
public class SKResult {

	// 返回代码
	private boolean result;
	// 错误信息
	private String respMsg;
	
	private Object obj;
	
	@Override
	public String toString() {
		return "SKResult [result=" + result + ", respMsg=" + respMsg + ", obj="
				+ obj + ", type=" + type + "]";
	}


	//处理方式:默认jsapi,为1时扫码
	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public SKResult(boolean result, String respMsg) {
		super();
		this.result = result;
		this.respMsg = respMsg;
	}

	public SKResult(boolean result, String respMsg, Object obj) {
		super();
		this.result = result;
		this.respMsg = respMsg;
		this.obj = obj;
	}

	public boolean isResult() {
		return result;
	}


	public void setResult(boolean result) {
		this.result = result;
	}


	public String getRespMsg() {
		return respMsg;
	}


	public void setRespMsg(String respMsg) {
		this.respMsg = respMsg;
	}


	public Object getObj() {
		return obj;
	}


	public void setObj(Object obj) {
		this.obj = obj;
	}
	

}

package com.impay.pushua.bean.base;


/**
 * 参数校验
 */
public class ValidField {
	
	/**
	 * 字段名
	 */
	private String name;
	/**
	 * 字段描述
	 */
	private String des;
	/**
	 * 为true必须校验
	 */
	private boolean isValid = false; 
	/**
	 * 校验规则
	 */
	private String[] rules;
	
	public String[] getRules() {
		return rules;
	}
	public void setRules(String[] rules) {
		this.rules = rules;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDes() {
		return des;
	}
	public void setDes(String des) {
		this.des = des;
	}
	public boolean isValid() {
		return isValid;
	}
	public void setValid(boolean isValid) {
		this.isValid = isValid;
	}
	public ValidField(String name, String des, boolean isValid, String[] rules) {
		super();
		this.name = name;
		this.des = des;
		this.isValid = isValid;
		this.rules = rules;
	}
}




查看原文链接 本文由系统自动采集,如有侵犯您的权益,请通知网站管理员,我们会及时处理 点我投诉
40% Complete (success)