数据校验工具类

TsThirdPartyCheck.java

package com.picc.claimshared.util;

import com.picc.claimshared.vo.TsThirdPartyVo;
import pdfc.framework.exception.BusinessException;
import java.math.BigDecimal;

/**
 * @description:
 * @author: chen_shixin
 * @time: 2021/11/29 0029
 */
public class TsThirdPartyCheck {



        public static void checkDoc(TsThirdPartyVo thirdPartyVo){
            Excel excel=new Excel();
//            thirdPartyVo.getBranchConut().toString();

            //不能为空
            StringLength.notNull(thirdPartyVo.getThirdPartyName(), "第三方公估机构全称不能为空!");
            StringLength.notNull(thirdPartyVo.getThirdPartyCode(), "第三方公估机构统一信用代码不能为空!");
            StringLength.notNull(thirdPartyVo.getThirdPartyContent(), "简介(业务范围、规模、优势介绍)不能为空!");
            StringLength.notNull(thirdPartyVo.getEstablishmentTime(), "成立时间不能为空!");
            TimeUtil.isPastDate(thirdPartyVo.getEstablishmentTime(),"成立时间不能超过当前时间");
            StringLength.notNull(thirdPartyVo.getRegisterCapital(), "注册资本金(万元)不能为空!");
            StringLength.notNull(thirdPartyVo.getBranchConut(), "行分支机构数量不能为空!");
            StringLength.Integer(thirdPartyVo.getBranchConut().toString(),"是否有效只能是正整数!" );
//            StringLength.notNull(tsPrpDcompanyVo.getAssnumber(), "公估师数量不能为空!");
            StringLength.notNull(thirdPartyVo.getUserName(), "联系人姓名不能为空!");
            StringLength.notNull(thirdPartyVo.getUserWorker(), "联系人职务不能为空!");
            StringLength.notNull(thirdPartyVo.getUserPhone(), "联系人电话不能为空!");
            StringLength.notNull(thirdPartyVo.getUserEmail(), "联系人邮箱地址不能为空!");
//            StringLength.notNull(tsPrpDcompanyVo.getIsBelongsCourt(), "是否属于法院司法鉴定名录中的鉴定机构不能为空!");
            StringLength.notNull(thirdPartyVo.getIsEffective(), "是否有效不能为空!");
//            StringLength.notNull(tsPrpDcompanyVo.getAppclasscode(), "合作险类不能为空!");
            //检验
            StringLength.Length(thirdPartyVo.getThirdPartyName(),50,"第三方公估机构全称不超过50个汉字");
            StringLength.isContainChinese(thirdPartyVo.getThirdPartyName(),"第三方公估机构全称只能是汉字");
            StringLength.Length(thirdPartyVo.getThirdPartyCode(),30,"第三方公估机构统一信用代码不超过30个汉字");
            StringLength.Length(thirdPartyVo.getThirdPartyContent(),500,"简介不超过500个汉字");
            StringLength.Decimal(thirdPartyVo.getRegisterCapital().toString(),"注册资本金(万元)只能是数字!");
            StringLength.Length(thirdPartyVo.getUserName(),50,"联系人姓名不超过50个汉字");
            StringLength.Length(thirdPartyVo.getUserWorker(),50,"联系人职务不超过50个汉字");
            StringLength.Length(thirdPartyVo.getUserPhone(),30,"联系人电话不超过30个汉字");
            StringLength.Length(thirdPartyVo.getUserEmail(),50,"联系人邮箱地址不超过50个汉字");
//            StringLength.Integer(tsPrpDcompanyVo.getIsBelongsCourt(),"是否属于法院司法鉴定名录中的鉴定机构只能是正整数!" );
            StringLength.Integer(thirdPartyVo.getIsEffective(),"是否有效只能是正整数!" );
//            StringLength.Number(tsPrpDcompanyVo.getWaterPicc(),"水险与人保公司合作范围只能是数字!" );
            //验证注册资金数据
            check(thirdPartyVo.getRegisterCapital());
            //检验统一社会信息代码
            boolean b = UnifiedCreditCodeUtils.validateUnifiedCreditCode(thirdPartyVo.getThirdPartyCode());
            if (!b) {
                throw new BusinessException("公估机构统一信用代码有误");
            }
//            判断手机号
            if (!excel.isValidPhoneNumber(thirdPartyVo.getUserPhone())){
                throw new BusinessException("手机号不正确");
            }
            //判断邮箱
            if (!excel.isValidEmail(thirdPartyVo.getUserEmail())){
                throw new BusinessException("邮箱不正确");
            }
            //判断是否有效
            String validStatus = thirdPartyVo.getIsEffective();
            if (validStatus != null && !"".equals(validStatus)) {
                int status= Integer.parseInt(validStatus);
                if (status !=0 && status !=1) {
                    throw new BusinessException("是否有效只能输入“0”或“1”");
                }
            }


        }

        /**
         * 检验注册资金
         */
        public static void check(BigDecimal bigDecimal){
            if (bigDecimal != null) {
                String s = bigDecimal.toString();
                boolean contains = s.contains(".");
                if (contains) {
                    String substring = s.substring(s.indexOf(".")+1);
                    System.out.println("substring:"+substring);
                    if (substring.length()>6) {
                        throw new BusinessException("注册资金最多6位小数");
                    }
                }
            }
        }


}

StringLength.java

package com.picc.claimshared.util;

import com.picc.common.util.StringUtil;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import pdfc.framework.exception.BusinessException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 检验
 * @author zhang
 */
public class StringLength {
    private static Logger log = LoggerFactory.getLogger(StringUtil.class);

    /**
     * 是否为空
     * @param object
     * @param message
     */
	public static void notNull(Object object, String message) {
		if (object == null || "".equals(object)) {
            System.out.println("object:"+object);
			throw new BusinessException(message);
		}
	}

    /**
     * 检验字符串长度
     * @param s
     * @param i
     * @param message
     */
   public static void Length(String s,int i, String message) {
       if (s!=null&&!"".equals(s)) {

               if (s.length() > i) {
                   throw new BusinessException(message);
               }
           }
   }

    /**
     * 汉字正则
     * @param str
     * @return
     */
   public static void isContainChinese(String str,String message) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
       for (int i = 0; i < str.length(); i++) {
           String c = String.valueOf(str.charAt(i));
           Matcher m = p.matcher(c);
        if (!m.find()) {
           throw new BusinessException(message);
        }
       }


    }
    /**
     * 检验是否为数字 和逗号(, ,)
     * @param s
     * @param message
     */
    public static void Number(String s,String message) {

        if (s!=null && !"".equals(s)){
            boolean numeric = isNumeric(s);
            if (!numeric) {
                throw new BusinessException(message);
            }
     }
   }
   /**
     * 数字 和逗号(, ,)正则
     * @param s
     * @return
     */
	public static boolean isNumeric(String s) {

        if (s != null && !"".equals(s.trim())) {

            boolean matches = s.matches("^[0-9,,]*$");
            if (matches){
                return true;
            }
        }
      return false;
    }
        /**
     * 检验是否为数字 和小数点(.)
     * @param s
     * @param message
     */
    public static void Decimal(String s,String message) {
        if (s!=null && !"".equals(s)){
            boolean numeric = isDecimal(s);
            if (!numeric) {
                throw new BusinessException(message);
            }
     }
   }
   /**
     * 数字 和小数点(.)正则
     * @param s
     * @return
     */
	public static boolean isDecimal(String s) {

        if (s != null && !"".equals(s.trim())) {

            boolean matches = s.matches("^[0-9.]*$");
            if (matches){
                return true;
            }
        }
      return false;
    }

    /**
     * 检验是否为正整数字
     */
    public static void Integer(String s,String message) {
        if (s!=null && !"".equals(s)){
            boolean numeric = isinteger(s);
            if (!numeric) {
                throw new BusinessException(message);
            }
     }
   }
    /**
     * 正整数字正则
     * @param s
     * @return
     */
	public static boolean isinteger(String s) {

        if (s != null && !"".equals(s.trim())) {
            boolean matches = s.matches("^[0-9]*$");
            if (matches){
                return true;
            }
        }
      return false;
    }
      /**
     * 验证字符串是否为指定日期格式
     *
     * @param rawDateStr 待验证字符串
     * @return 有效性结果, true 为正确, false 为错误
     */
    public static void dateStrIsValid(String rawDateStr,String message) {
        String pattern="yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        Date date ;
            // 转化为 Date类型测试判断
        try {
            date = dateFormat.parse(rawDateStr);
            boolean equals = rawDateStr.equals(dateFormat.format(date));
            if (!equals){
                throw new BusinessException(message);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

TimeUtil

package com.picc.claimshared.util;

import pdfc.framework.exception.BusinessException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 描述:时间工具类
 *
 * @author csx
 * @version 1.0
 * @date 2021/12/06 15:04:24
 */
public class TimeUtil {
/**
 * 描述:判断时间是否超过当前日期
 * @Param: [str, message]
 * @Return: void
 * @author csx
 * @date 2021/12/6 0006 20:10
 * 
 */

        public static void isPastDate(Date str,String message){
            boolean flag = false;
            Date nowDate = new Date();
            //格式化日期
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

//            String dt = sdf.format(str);
//            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+dt);
            //调用Date里面的before方法来做判断
            if (str.after(nowDate)){
                throw new BusinessException(message);

            }
        }


    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hibernate Validator是一种基于注解的校验框架,用于验证JavaBean中的数据。它提供了一种简单易用的方式来确保数据的完整性和一致性,在实际开发中被广泛应用。 下面是一个校验工具类的示例: ```java import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; public class ValidatorUtils { private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验对象 * * @param obj 待校验对象 * @param groups 待校验的组 * @throws Exception 校验不通过,则报Exception异常 */ public static void validateEntity(Object obj, Class<?>... groups) throws Exception { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj, groups); if (!constraintViolations.isEmpty()) { StringBuilder msg = new StringBuilder(); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { msg.append(constraintViolation.getMessage()).append("<br>"); } throw new Exception(msg.toString()); } } } ``` 使用示例: ```java public class User { @NotNull(message = "用户名不能为空") private String username; @NotNull(message = "密码不能为空") private String password; // getter and setter } public class Test { public static void main(String[] args) { User user = new User(); user.setUsername(null); user.setPassword(null); try { ValidatorUtils.validateEntity(user); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意事项: - 需要在JavaBean的属性上添加相应的注解; - 需要在校验工具类中使用`Validation.buildDefaultValidatorFactory().getValidator()`方法获取`Validator`对象; - 可以通过`groups`参数指定需要校验的组,如果不指定,则校验所有组的规则。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值