The java check entity class only checks non-empty fields

Scenes

The third-party calls the interface and passes parameters. Some values ​​only receive fixed enumeration values, and no judgment is made for empty fields.

solve

Custom verification, the verification field can only be a specific enumeration value, and when a field is empty, it will be verified and an error message will be returned.

(The empty field is the case where you do not want to check)

At this time, you can add a judgment in the tool class to skip the processing of the error message of the empty field verification.

Verification code:

Returning an error message indicates that the verification is not correct, but the error message of the empty field will not be spelled later, so the verification of the empty field is skipped.

 private static Validator validator;
    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static String ignoreEmpty(Object object){
            //使用Gson 避免实体类对象有JsonField注解转json会以注解为准
            Gson gson = new Gson();
            String json = gson.toJson(object);
            JSONObject jsonObject = JSON.parseObject (json);
            StringBuilder msg = new StringBuilder();
            //返回的实体可能有些字段是没有的,所以不能单纯by对象validate校验就完事
            Set<ConstraintViolation<Object>> constraintViolationSet= validator.validate(object);
            if(!constraintViolationSet.isEmpty()){
                for (ConstraintViolation<Object> constraint:constraintViolationSet) {
                   String fieldName = constraint.getPropertyPath().toString();
                   if(null == jsonObject){//字段为空校验出来的错误信息不拼接,认为是可过的
                       continue;
                   }
                    msg.append(constraint.getMessage());
                }
            }
            return msg.toString();
    }

The java custom verification entity class can only be a fixed enumeration value, refer to:

Hibernate validation, spring validation custom validation ------ can only be a specified value_@valid check attribute value is a fixed value_ldcn614's blog-CSDN blog

Guess you like

Origin blog.csdn.net/ss_Tina/article/details/129850454