[英]Better way of using JSR303 annotations in Spring MVC to check whitespaces only
Im using a custom validation on a textbox that checks if entered sentence contains only white spaces The code is as below 我在文本框上使用自定义验证,检查输入的句子是否只包含空格代码如下
@Retention(value = RetentionPolicy.RUNTIME)
@javax.validation.Constraint(validatedBy = SmsMessageContent.SmsMessageContentValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Documented
public @interface SmsMessageContent {
public class SmsMessageContentValidator implements
ConstraintValidator<SmsMessageContent, String> {
@Override
public void initialize(final SmsMessageContent constraintAnnotation) {
}
@Override
public boolean isValid(final String value,
final ConstraintValidatorContext context) {
if (value == null)
return true;
try {
if (value.matches("^\\s*$")) {
context.buildConstraintViolationWithTemplate("{message.sms.content.not.empty}")
.addConstraintViolation();
context.disableDefaultConstraintViolation();
return false;
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
The above annotation im using in another class as 以上注释我在另一个类中使用
public class SmsMessageForm {
@SmsMessageContent
private String smsChannelContent = "";
Is there any annotation in JSR303 or JSR330 that can be used directly on JSR303或JSR330中是否有可以直接使用的注释
private String smsChannelContent = "";
instead of writing another annotation like what I have used to check for a whitespaces only? 而不是像我用来检查空格的那样写另一个注释?
I believe @Pattern
does just that 我相信
@Pattern
就是@Pattern
@Pattern("^\\s*$")
private String smsChannelContent = "";
The javadoc states javadoc说
The annotated String must match the following regular expression.
带注释的String必须与以下正则表达式匹配。
So use the pattern you need. 所以使用你需要的模式。 I wasn't sure if you wanted to check against whitespace or for whitespace.
我不确定你是想检查空格还是空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.