如何在休眠状态下将数字字符串验证为数字?

2022-09-01 18:15:51

我必须使用哪些注释进行休眠验证,以验证要应用于以下内容的字符串:

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

如何应用数字验证?我会在这里使用吗?@Digits(fraction = 0, integer = 6)


答案 1

您可以将所有约束替换为单个 .这意味着长度为 6 的字符串,其中每个字符都是一个数字。@Pattern(regexp="[\\d]{6}")


答案 2

您还可以创建自己的休眠验证批注。
在下面的示例中,我创建了一个名为 的验证注释。具有此注释的字段将使用类的方法进行验证。EnsureNumberisValidEnsureNumberValidator

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

}

你可以这样使用它,

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

推荐