java常规校验工具类

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);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值