注释&正则表达式 [英] annotation & regex

查看:43
本文介绍了注释&正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用注释 + 正则表达式验证电子邮件.我尝试使用以下内容:

I need to do a validation of an e-mail using annotation + regex. I tried to use the following:

@NotNull
@Pattern(regexp=".+@.+\\.[a-z]+")
private String email;

但是,当电子邮件字段中的电子邮件地址不正确时,我不知道如何打印错误消息.有什么想法吗?

However, I don't know how to print an error message when I have an incorrect e-mail address in the email field. Any ideas?

推荐答案

首先,您应该将 message 属性添加到您的 Pattern 注释中.假设您的邮件变量是某个类 User 的一部分:

First you should add a message attribute to your Pattern annotation. Assume that your mail variable is part of some class User:

class User{
@NotNull
@Pattern(regexp=".+@.+\\.[a-z]+", message="Invalid email address!")
private String email;
}

那么你应该定义一个验证器:

Then you should define a validator:

ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
User user = new User();
user.setEmail("user@gmail.com");
Set<ConstraintViolation<User>> constraintViolations = validator
        .validate(user);

然后查找验证错误.

for (ConstraintViolation<Object> cv : constraintViolations) {
      System.out.println(String.format(
          "Error here! property: [%s], value: [%s], message: [%s]",
          cv.getPropertyPath(), cv.getInvalidValue(), cv.getMessage()));
}

这篇关于注释&amp;正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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