package com.jeeplus.modules.bigdata.util;
import com.alibaba.fastjson2.JSONObject;
import java.util.regex.Pattern;
public class VerificationParameterUtil {
public static void verification(JSONObject obj, String str, boolean required,String clazz,int length) throws Exception {
String strData = obj.getString(str);
if(required==true){
if(strData==null)throw new Exception( str + " is required");
if(strData.equals(""))throw new Exception( str + " is required");
if(strData.equals(" "))throw new Exception( str + " is required");
}
if(length>0 && strData!=null && !strData.equals("")){
// 英文字母长度为准
if(strData.length()>length) throw new Exception( str + " is longer than expected");
}
if(clazz.equals("String")){
if (strData instanceof String) {
}
}
if(clazz.equals("Integer")){
if(strData!=null && !isInteger(strData) ){
throw new Exception( str + " must be an integer");
}
}
if(clazz.equals("Double") ){
if(strData!=null && !isNumeric(strData)){
throw new Exception( str + " must be an double");
}
}
}
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-+]?\\d+$");
return pattern.matcher(str).matches();
}
/**
* 判断字符串是否为数字(包括小数)
*
* @param str 需要判断的字符串
* @return 如果是数字返回true,否则返回false
*/
public static boolean isNumeric(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
// 正则表达式规则,匹配整数和小数
// ^表示字符串的开始,$表示字符串的结束,中间的+表示匹配前面的字符或组一次或多次
// \D* 表示非数字字符可以出现0次或多次(小数点前后都可能有空白字符)
// \d+ 表示至少有一位数字
// (\.\d+)? 表示小数点和至少一位数字可以有0次或1次出现(小数点前后的数字)
String regex = "^(\\d+(\\.\\d+)?)$";
return str.matches(regex);
}
}
09-21
1180
