@Email 注解用来约束字段的值必须是一个合法的邮箱地址,注解源码如下:
@Documented @Constraint(validatedBy = { }) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @ReportAsSingleViolation @Pattern(regexp = "") public @interface Email { String message() default "{org.hibernate.validator.constraints.Email.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; // 注释字符串必须匹配的附加正则表达式,默认值是任意字符串('.*') @OverridesAttribute(constraint = Pattern.class, name = "regexp") String regexp() default ".*"; // 与 regexp() 结合使用,以指定正则表达式选项 @OverridesAttribute(constraint = Pattern.class, name = "flags") Pattern.Flag[] flags() default { }; // 在同一元素上定义多个 @Email 注解 @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented public @interface List { Email[] value(); } }
注意:message、groups、payload 属性用法参考 @NotNull 注解,并且 @Email 注解使用的是 org.hibernate.validator.constraints.Email 而不是 javax.validation 中的 @Email 注解。
示例:
package com.hxstrive.validation; import lombok.Builder; import lombok.Data; import org.hibernate.validator.HibernateValidator; import org.hibernate.validator.constraints.Email; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; /** * 注解元素必须为有效的电子邮件地址 * @author HuangXin * @since 1.0.0 2024/1/10 9:13 */ @Data @Builder public class EmailDemo { @Email(message = "必须是有效邮箱地址") private String addr; public static void main(String[] args) { EmailDemo.builder().addr("hxstrive@163.com").build().validator("case1"); // OK EmailDemo.builder().addr("hxstrive@163").build().validator("case2"); // OK EmailDemo.builder().addr("@163.com").build().validator("case3"); // Fail EmailDemo.builder().addr(null).build().validator("case4"); // OK } private void validator(String caseName) { validator(caseName, this); } private <T> void validator(String caseName, T obj) { // 手动调用 API 对定义了注解的字段进行校验 Validator validator = Validation.byProvider(HibernateValidator.class).configure() .failFast(true).buildValidatorFactory().getValidator(); Set<ConstraintViolation<T>> set = validator.validate(obj); if (set.size() > 0) { // 校验失败 System.out.println(caseName + " :: Fail :: " + set.iterator().next().getMessage()); } else { // 校验通过 System.out.println(caseName + " :: Succeed"); } } }
运行示例,输出如下:
case1 :: Succeed case2 :: Succeed case3 :: Fail :: 必须是有效邮箱地址 case4 :: Succeed