Spring Boot 验证 - 二选一不为空 [英] Spring Boot validation - one from two not null

查看:102
本文介绍了Spring Boot 验证 - 二选一不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证 Spring Boot 中的两个字段之一是否不为空?

I'm trying to validate if one of two fields are not null in Spring Boot?

我已经在主对象的方法类中设置了:

I have set that in the method class for the main object:

@NotNull(message = "Username field is required")
private String username;

@NotNull(message = "Email field is required")
private String email;

但这需要两个字段都不是空的.然后我进行了此处描述的自定义验证 https://lmonkiewicz.com/programming/get-noticed-2017/spring-boot-rest-request-validation/ 但我无法让该示例发挥作用.我必须坚持

but that will require to have both fields not null. Then I went with custom validation described here https://lmonkiewicz.com/programming/get-noticed-2017/spring-boot-rest-request-validation/ but I wasn't able to get that example to work. I have to stuck on

用户类声明:

@CombinedNotNull(fields = {"username","email"})
public class User implements {

    private long id = 0L;
    @NotNull(message = "First name field is required")
    private String firstName;

    @NotNull(message = "Last name field is required")
    private String lastName;

    private String username;
    private String email;

    @NotNull(message = "Status field is required")
    private String status;

    ...all methods here...
    ...setters and getters...

}

CombibnedNotNull 类:

CombibnedNotNull class:

@Documented
@Retention(RUNTIME)
@Target({ TYPE, ANNOTATION_TYPE })
@Constraint(validatedBy = userValidator.class)
public @interface CombinedNotNull {
        String message() default "username or email is required";
        Class<?>[] groups() default { };
        Class<? extends Payload>[] payload() default { };
}

userValidator 类:

userValidator class:

@Component
public class userValidator implements ConstraintValidator<CombinedNotNull, User> {

    @Override
    public void initialize(final CombinedNotNull combinedNotNull) {
        fields = combinedNotNull.fields();
    }

    @Override
    public boolean isValid(final User user, final ConstraintValidatorContext context) {
        final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(user);

        for (final String f : fields) {
            final Object fieldValue = beanWrapper.getPropertyValue(f);

            if (fieldValue == null) {
                return false;
            }
        }

        return true;
    }
}

是否有其他方法可以完成此操作,还是我应该使用该页面中的复杂"示例?

Is there any other way to get this done or should I go with the "complex" example from that page?

推荐答案

我会尽力为您实现它(即使我没有 IDE).
ConstraintValidator#initialize 中,您可以获取不能null 的已配置字段的名称.

I'll try to implement it for you (even if I'm without an IDE).
Inside ConstraintValidator#initialize you can get a hold of the configured fields' names which cannot be null.

@Override
public void initialize(final CombinedNotNull combinedNotNull) {
    fields = combinedNotNull.fields();
}

ConstraintValidator#isValid 中,您可以使用这些字段的名称来检查 Object 字段.

Inside ConstraintValidator#isValid you can use those fields' names to check the Object fields.

@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(value);
    
    for (final String f : fields) {
       final Object fieldValue = beanWrapper.getPropertyValue(f);
       
       if (fieldValue == null) {
          return false;
       }
    }

    return true;
}

注释:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy = CombinedNotNullValidator.class)
public @interface CombinedNotNull {
    String message() default "username or email is required";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Fields to validate against null.
     */
    String[] fields() default {};
}

注释可以应用为

@CombinedNotNull(fields = {
      "fieldName1",
      "fieldName2"
})
public class MyClassToValidate { ... }

要了解如何创建类级别的约束注释,请始终参考官方文档.文档

To learn how to create a Class-level constraint annotation, refer always to the official documentation. Docs

这篇关于Spring Boot 验证 - 二选一不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆