2013-07-05 1 views
0
  1. bean 유효성 검사에서 정확하게 일치하는 문자열을 검증하려고합니다. @Pattern을 사용해야합니까, 아니면 다른 방법이 있습니까?
  2. @Pattern이가는 길인 경우 regex은 무엇입니까?
  3. 동일한 필드에서 두 개의 서로 다른 그룹에 두 개의 @Pattern 주석을 사용할 수 있습니까?

답변

4

bean 유효성 검사에서 정확하게 일치하는 문자열을 검증하려고합니다. @Pattern을 사용해야합니까, 아니면 그렇게 할 다른 방법이 있습니까?

당신은 @Pattern를 사용하거나 아주 쉽게 사용자 정의 제약 조건을 구현할 수 중 하나 @Pattern은 무엇을 갈 수있는 방법입니다

public class MatchesValidator implements ConstraintValidator<Matches, String> { 

    private String comparison; 

    @Override 
    public void initialize(Matches constraint) { 
     this.comparison = constraint.value(); 
    } 

    @Override 
    public boolean isValid(
     String value, 
     ConstraintValidatorContext constraintValidatorContext) { 

     return value == null || comparison.equals(value); 
    } 
} 

경우이 같은 발리로

@Documented 
@Constraint(validatedBy = MatchesValidator.class) 
@Target({ METHOD, CONSTRUCTOR, PARAMETER, FIELD }) 
@Retention(RUNTIME) 
public @interface Matches { 
    String message() default "com.example.Matches.message"; 
    Class<?>[] groups() default {}; 
    Class<? extends Payload>[] payload() default {}; 
    String value(); 
} 

regex은 무엇입니까?

기본적으로 일치시킬 문자열 만 입력하면 [\^$. |? * +()와 같은 특수 문자 만 이스케이프 처리하면됩니다. 자세한 내용은 this reference을 참조하십시오.

같은 필드에서 두 개의 다른 그룹에 두 개의 @Pattern 주석을 사용할 수 있습니까?

예, 방금하여 @Pattern.List 주석 사용

@Pattern.List({ 
    @Pattern(regex = "foo", groups = Group1.class), 
    @Pattern(regex = "bar", groups = Group2.class) 
}) 
+0

당신이 정확한 문자열 일치를위한 정규식을 업데이트하십시오 할 수 있습니까? –

+1

예. '@Pattern (regex = "foo")'또는 @Pattern (regex = "really \\?")' – Gunnar

+0

고마워, 메이트! 그게 도움이! –