Java 如何使用休眠将数字字符串验证为数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19537664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate number string as digit with hibernate?
提问by membersound
Which annotations would I have to use for Hibernate Validation to validate a String to apply to the following:
对于 Hibernate 验证,我必须使用哪些注释来验证字符串以应用于以下内容:
//should always have trimmed length = 6, only digits, only positive number
@NotEmpty
@Size(min = 6, max = 6)
public String getNumber {
return number.trim();
}
How can I apply digit validation? Would I just use @Digits(fraction = 0, integer = 6)
here?
如何应用数字验证?我会@Digits(fraction = 0, integer = 6)
在这里使用吗?
采纳答案by Hardy
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.
您可以将所有约束替换为单个@Pattern(regexp="[\\d]{6}")
. 这意味着一个长度为 6 的字符串,其中每个字符都是一个数字。
回答by George Siggouroglou
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.
您还可以创建自己的休眠验证注释。
在下面的示例中,我创建了一个名为 name 的验证注释EnsureNumber
。带有此注释的字段将使用类的isValid
方法进行验证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);
}
}
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;