英文:
How to apply size annotation for a field which can be either of two sizes
问题
在我的Spring Boot应用程序中,我在DTO的一个字段上进行了大小验证。现在根据新的要求,字段大小可以是18或36。以前是36,所以我是这样做的:
@Size.List({
@Size(min = 18, max = 18, message = "id length should be 18"),
@Size(min = 36, max = 36, message = "id length should be 36")
})
现在我必须对两种大小进行验证,有没有办法在注解本身完成这个操作?
谢谢,
英文:
In my spring boot application I have a size validation on one of field in my dto. Now as per new requirement field size can be either 18 or 36. Earlier it was 36 so I had done like this:
@Size(min=36,max = 36,message = "id length should be 36")
Now as I have to validate against two sizes, Is there any way to do it with the annotation itself ?
Thanks,
答案1
得分: 2
制作一个自定义验证器注解。
在 CustomSize.java 中
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = CustomSizeValidator.class)
@Documented
public @interface CustomSize {
String message() default "{CustomSize.invalid}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
在 CustomSizeValidator.java 中
class CustomSizeValidator implements ConstraintValidator<CustomSize, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
try {
if(value.length() == 18 || value.length() == 36) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
}
在你的 POJO 代码中使用这个注解。
@CustomSize
private String xyz;
或者使用 @Pattern
@Pattern(regexp = "^(?:[A-Za-z0-9]{18}|[A-Za-z0-9]{36})$")
有关 Pattern 的更多信息请参见这里 -> https://stackoverflow.com/a/34311990/1459174
英文:
Make a custom validator Annotation.
In CustomSize.java
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = CustomSizeValidator.class)
@Documented
public @interface CustomSize{
String message() default "{CustomSize.invalid}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
In CustomSizeValidator.java
class CustomSizeValidator implements ConstraintValidator<CustomSize, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
try {
if(value.length()==18 || value.length()==36){
return true;
}else{
return false;
}
} catch (Exception e) {
return false;
}
}
}
Use this in your POJO code.
@CustomSize
private String xyz;
OR
use @Pattern
@Pattern(regexp = "^(?:[A-Za-z0-9]{18}|[A-Za-z0-9]{36})$")
For Pattern see more here -> https://stackoverflow.com/a/34311990/1459174
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论