【问题标题】:Choosing validation according to enum value根据枚举值选择验证
【发布时间】:2019-12-29 05:17:51
【问题描述】:

我正在编写一个类,该类应定义具有相关帐单信息的信用卡数据。位数根据信用卡的类型而变化。所以我想设置一个枚举并根据枚举的类型更改验证注释

import java.time.LocalDate;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data @AllArgsConstructor @EqualsAndHashCode(callSuper=true)
@Entity
@Table(name="BillingInfo")
public class BillingInfo extends PersonalInfo {

    @NotBlank
    private String billingAddress;


    private String creditCardId;

    ***@CustomValidatorHere***
    private Integer CreditCardCCV;

    private Integer CreditCardNumber;
    private LocalDate CreditCardEXPdate;

    @Enumerated(EnumType.STRING)
    private CreditCardType creditCardType;

    @OneToMany
    private Set<Order> orders;

    public enum CreditCardType {
        Type1, Type2, Type3
    }

}

我正在考虑使用 Passey 并创建一个服务,其中 ConstraintValidator 根据 CreditCardType 动态变化,并带有一个 switch 案例

还有更直接的解决方案吗?在 jpa 和 spring 文档上找不到任何东西

谢谢

【问题讨论】:

  • 为什么不简单地在 BillingInfo 类而不是 CreditCardNumber 字段上声明验证?然后,您将能够从验证器内部访问 CreditCardCCVCreditCardType
  • 这是一个很好的观点。您的意思是创建一个约束并将“@ValidBillingInfo”放在类声明中吗?我能否在使用 Angular 和 Bootstrap 通过 @Controller 和 Error 类渲染模板时管理错误??
  • 可能。看我的回答

标签: spring validation jpa enums spring-annotations


【解决方案1】:

为什么不简单地在BillingInfo 类而不是CreditCardNumber 字段上声明验证?然后,您将能够从验证器内部访问 CreditCardCCVCreditCardType

我能否在使用 Angular 和 Bootstrap 通过 @Controller 和 Error 类渲染模板时管理错误

我不知道您的确切设置,但您能够将约束验证放在类级别,并且仍然将错误附加到 CreditCardCCV 属性,具体使用:

constraintValidatorContext.buildConstraintViolationWithTemplate(
        constraintValidatorContext.getDefaultConstraintMessageTemplate())
    .addPropertyNode("CreditCardCCV")
    .addConstraintViolation()

请注意,您可能还想使用constraintViolationContext.disableDefaultConstraintViolation() 来避免违规被报告两次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多