java 用于验证字段的@Size 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38224733/
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
@Size annotation to validate a field
提问by Andy
I need to validate a field - secPhoneNumber (secondary phone #). I need to satisfy below conditions using JSR validation
我需要验证一个字段 - secPhoneNumber(辅助电话号码)。我需要使用 JSR 验证满足以下条件
- The field can be empty/null
- Otherwise, the data must be of length 10.
- 该字段可以为空/null
- 否则,数据长度必须为 10。
I tried the code below. The field is always getting validated on form submission. How do I validate the field to be of length 10 only when it is not empty?
我尝试了下面的代码。该字段总是在表单提交时得到验证。仅当字段不为空时,如何验证字段的长度为 10?
Spring Form:
弹簧形式:
<form:label path="secPhoneNumber">
Secondary phone number <form:errors path="secPhoneNumber" cssClass="error" />
</form:label>
<form:input path="secPhoneNumber" />
Bean
豆角,扁豆
@Size(max=10,min=10)
private String secPhoneNumber;
回答by Andy
Following patterns work
以下模式有效
- @Pattern(regexp="^(\s*|[a-zA-Z0-9]{10})$")
- @Pattern(regexp="^(\s*|\d{10})$")
- @Pattern(regexp="^(\s*|[a-zA-Z0-9]{10})$")
- @Pattern(regexp="^(\s*|\d{10})$")
// ^ # Start of the line
// \s* # A whitespace character, Zero or more times
// \d{10} # A digit: [0-9], exactly 10 times
//[a-zA-Z0-9]{10} # a-z,A-Z,0-9, exactly 10 times
// $ # End of the line
Reference: Validate only if the field is not Null
参考:仅当字段不为空时才验证
回答by cralfaro
I think for readability and to use in future times i would create my custom validation class, you only should follow this steps:
我认为为了可读性和将来使用我会创建我的自定义验证类,您只应该按照以下步骤操作:
Add your new custom annotation to your field
@notEmptyMinSize(size=10) private String secPhoneNumber;
Create the custom validation classes
@Documented @Constraint(validatedBy = notEmptyMinSize.class) @Target( { ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface notEmptyMinSize { int size() default 10; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Add your business logic to your validation
public class NotEmptyConstraintValidator implements ConstraintValidator<notEmptyMinSize, String> { private NotEmptyMinSize notEmptyMinSize; @Override public void initialize(notEmptyMinSize notEmptyMinSize) { this.notEmptyMinSize = notEmptyMinSize } @Override public boolean isValid(String notEmptyField, ConstraintValidatorContext cxt) { if(notEmptyField == null) { return true; } return notEmptyField.length() == notEmptyMinSize.size(); } }
将您的新自定义注释添加到您的字段
@notEmptyMinSize(size=10) private String secPhoneNumber;
创建自定义验证类
@Documented @Constraint(validatedBy = notEmptyMinSize.class) @Target( { ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface notEmptyMinSize { int size() default 10; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
将您的业务逻辑添加到您的验证中
public class NotEmptyConstraintValidator implements ConstraintValidator<notEmptyMinSize, String> { private NotEmptyMinSize notEmptyMinSize; @Override public void initialize(notEmptyMinSize notEmptyMinSize) { this.notEmptyMinSize = notEmptyMinSize } @Override public boolean isValid(String notEmptyField, ConstraintValidatorContext cxt) { if(notEmptyField == null) { return true; } return notEmptyField.length() == notEmptyMinSize.size(); } }
And now you could use this validation in several fields with different sizes.
现在您可以在多个不同大小的字段中使用此验证。
Here another example you can follow example
这里是另一个例子,你可以按照例子