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
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("^\\s*$")
private String smsChannelContent = "";
The javadoc states
The annotated String must match the following regular expression.
So use the pattern you need. I wasn't sure if you wanted to check against whitespace or for whitespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.