Spring boot starter data rest, @Notnull constraint not working

后端 未结 4 1362
陌清茗
陌清茗 2020-12-18 05:43

I am trying to add @NotNull constraint into my Person object but I still can @POST a new Person with a null email. I am using Spring boot rest with MongoDB.

Entity c

4条回答
  •  难免孤独
    2020-12-18 06:23

    i found it better to make my own version of @NotNull annotation which validates empty string as well.

    @Documented
    @Constraint(validatedBy = NotEmptyValidator.class)
    @Target({ElementType.METHOD, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface NotEmpty {
    
    
        String message() default "{validator.notEmpty}";
    
        Class[] groups() default {};
    
        Class[] payload() default {};
    
    }
    
    public class NotEmptyValidator implements ConstraintValidator {
    
        @Override
        public void initialize(NotEmpty notEmpty) { }
    
        @Override
        public boolean isValid(Object obj, ConstraintValidatorContext cxt) {
            return obj != null && !obj.toString().trim().equals("");
        }
    
    }
    

提交回复
热议问题