Created
June 11, 2014 19:06
-
-
Save rkroll/4a9cb70334a5dc0d4bf0 to your computer and use it in GitHub Desktop.
Bean Validation Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class User { | |
@NotNull | |
private String email; | |
@ValidUsername | |
private String username; | |
@NotNull | |
private String name; | |
@NotNull(message = "password.null") | |
@Size(min = 3, max = 255, message = "password.length") | |
private String password; | |
} | |
@NotEmpty | |
@Length(min = 3, max = 100) | |
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) | |
@Retention(RUNTIME) | |
@Constraint(validatedBy = UsernameValidationConstraint.class) | |
@Documented | |
public @interface ValidUsername { | |
String message() default "{m2.constraints.username.invalid.message}"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
} | |
public class UsernameValidationConstraint implements ConstraintValidator<ValidUsername, String> { | |
@SuppressWarnings("unused") | |
private String message; | |
// any lowercase letter, number, and the following special chars: . @ _ - | |
private static final String PATTERN_STRING = "^[a-zA-Z0-9\\.@_-]+$"; | |
private Pattern pattern = Pattern.compile(PATTERN_STRING); | |
@Override | |
public void initialize(ValidUsername constraintAnnotation) { | |
message = constraintAnnotation.message(); | |
} | |
@Override | |
public boolean isValid(String value, ConstraintValidatorContext context) { | |
boolean valid = false; | |
if (value != null) { | |
valid = pattern.matcher(value).matches(); | |
} | |
return valid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment