2013-10-23 19 views
8

Những chú thích tôi sẽ phải sử dụng cho Hibernate Validation để xác nhận một String để áp dụng những điều sau đây:Làm cách nào để xác thực chuỗi số dưới dạng chữ số với hibernate?

//should always have trimmed length = 6, only digits, only positive number 
@NotEmpty 
@Size(min = 6, max = 6) 
public String getNumber { 
    return number.trim(); 
} 

Làm thế nào tôi có thể nộp đơn xác nhận chữ số? Tôi có sử dụng @Digits(fraction = 0, integer = 6) ở đây không?

Trả lời

11

Bạn có thể thay thế tất cả các ràng buộc của mình bằng một đơn @Pattern(regexp="[\\d]{6}"). Điều này sẽ ngụ ý một chuỗi có chiều dài 6, trong đó mỗi ký tự là một chữ số.

6

Bạn cũng có thể tạo chú thích xác thực ngủ đông của riêng mình.
Trong ví dụ bên dưới, tôi đã tạo chú thích xác thực có tên EnsureNumber. Các trường có chú thích này sẽ xác thực bằng phương thức isValid của lớp EnsureNumberValidator.

@Constraint(validatedBy = EnsureNumberValidator.class) 
@Target({ ElementType.FIELD }) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface EnsureNumber { 

    String message() default "{PasswordMatch}"; 

    Class<?>[] groups() default {}; 

    Class<? extends Payload>[] payload() default {}; 

    boolean decimal() default false; 

} 

public class EnsureNumberValidator implements ConstraintValidator<EnsureNumber, Object> { 
    private EnsureNumber ensureNumber; 

    @Override 
    public void initialize(EnsureNumber constraintAnnotation) { 
     this.ensureNumber = constraintAnnotation; 
    } 

    @Override 
    public boolean isValid(Object value, ConstraintValidatorContext context) { 
     // Check the state of the Adminstrator. 
     if (value == null) { 
      return false; 
     } 

     // Initialize it. 
     String regex = ensureNumber.decimal() ? "-?[0-9][0-9\\.\\,]*" : "-?[0-9]+"; 
     String data = String.valueOf(value); 
     return data.matches(regex); 
    } 

} 

Bạn có thể sử dụng nó như thế này,

@NotEmpty 
@Size(min = 6, max = 6) 
@EnsureNumber 
private String number1; 

@NotEmpty 
@Size(min = 6, max = 6) 
@EnsureNumber(message = "Field number2 is not valid.") 
private String number2; 

@NotEmpty 
@Size(min = 6, max = 6) 
@EnsureNumber(decimal = true, message = "Field number is not valid.") 
private String number3; 
Các vấn đề liên quan