2012-04-02 5 views
5

annotation + regex를 사용하여 전자 메일의 유효성 검사를 수행해야합니다.annotation & regex

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

그러나, 나는 이메일 필드에 잘못된 이메일 주소가 때 오류 메시지를 인쇄하는 방법을 모른다 : 나는 다음과 같은 사용했습니다. 어떤 아이디어?

+1

. 쉬운 답변 :'System.out.println (...)':) – Thomas

+3

질문에 대해 미안하지만 왜 @Email 주석을 사용하지 않습니까? – Peterino

답변

8

먼저 Pattern 주석에 message 속성을 추가해야합니다.

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

그런 다음 당신이 발리를 정의해야합니다 :

ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); 
Validator validator = vf.getValidator(); 
User user = new User(); 
user.setEmail("[email protected]"); 
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())); 
} 
0

:

유효성 검증을하고 그 메시지를 인쇄하려는 방법에 따라 달라집니다
@NotNull 
@Email(message = "This email address is invalid") 
private String email;