如何验证 JPA 实体中的电子邮件字符串

问题描述 投票:0回答:6

我的数据库中有一个长度为 512 的列。 它将包含多个用“;”分隔的电子邮件地址。 如何验证实体中其各自的变量,以便所有电子邮件地址都有效。

列表将不起作用,因为我需要将其保留在列中。数据如下:

@Basic
@Column(name = "CC_EMAIL_ADDRESS", nullable = true, length = 512)
private String emailCC;
hibernate jpa ejb-3.2
6个回答
2
投票

我在我的项目中使用这种方式取得了良好的成功

@NotEmpty
@Email
@Size(max = 255)
@Column(unique = true)
private String email;


@PrePersist
@PreUpdate
private void prepareData(){
    this.email = email == null ? null : email.toLowerCase();
}

1
投票

使用

javax.validation
库。如果您设置尝试持久化
email
时验证失败,则会抛出验证异常,或者您可以从
ValidatorFactory
开始进行手动验证。

@NotNull(message="{email.required}")
@Pattern(regexp = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
        + "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
        + "(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9]"
        + "(?:[A-Za-z0-9-]*[A-Za-z0-9])?",
        message = "{invalid.email}")
private String email;

0
投票

您可以在实体中使用 @PrePersist 回调事件来验证电子邮件,然后再将其保存到数据库。

@PrePersist
public void validateEmails(){
    //Validate Here
}

或者您可以在实体中创建一个setter方法并验证setter方法中的数据。


0
投票

您可以创建自定义约束

@MyCustomConstraint
private String emailCC;

其中

@MyCustomConstraint
将是您的新注释。


0
投票

使用已验证和正则表达式:

@Basic
@Pattern(regexp = "\\w+@\\w+\\.\\w+(,\\s*\\w+@\\w+\\.\\w+)*")
@Column(name = "CC_EMAIL_ADDRESS", nullable = true, length = 512)

0
投票
@Column(name = "user_email", nullable = false, unique = true)
@NotBlank(message = "user email is required")
@Email
@Size(max = 200)
private String userEmail;
© www.soinside.com 2019 - 2024. All rights reserved.