How to validate number string as digit with hibernate?

限于喜欢 提交于 2019-12-04 23:10:50

You could replace all your constraints with a single @Pattern(regexp="[\\d]{6}"). This would imply a string of length six where each character is a digit.

You can also create your own hibernate validation annotation.
In the example below I created a validation annotation with name EnsureNumber. Fields with this annotation will validate with the isValid method of the EnsureNumberValidator class.

@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);
    }

}

You can use it like this,

@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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!