Created
April 9, 2012 09:42
-
-
Save roalcantara/2342555 to your computer and use it in GitHub Desktop.
JAVA > Hibernate > Custom Validator Simple Sample
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
package com.xpto.domain.model.validator; | |
import javax.validation.Constraint; | |
import javax.validation.Payload; | |
import java.lang.annotation.*; | |
@Target(ElementType.FIELD) | |
@Retention(RetentionPolicy.RUNTIME) | |
@Constraint(validatedBy = PhotoExtensionValidator.class) | |
@Documented | |
public @interface PhotoExtension { | |
String message() default "Extension not valid"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
PhotoExtensionType extension(); | |
} | |
public enum PhotoExtensionType { | |
JPG, | |
GIF | |
} | |
package com.xpto.domain.model.validator; | |
import javax.validation.ConstraintValidator; | |
import javax.validation.ConstraintValidatorContext; | |
public class PhotoExtensionValidator implements ConstraintValidator<PhotoExtension, String> { | |
private PhotoExtensionType extension; | |
private String message; | |
@Override | |
public void initialize(final PhotoExtension constraintAnnotation) { | |
this.extension = constraintAnnotation.extension(); | |
this.message = constraintAnnotation.message(); | |
} | |
@Override | |
public boolean isValid(final String value, final ConstraintValidatorContext context) { | |
return value == null ? true : | |
value.toUpperCase().endsWith(this.extension.toString().toUpperCase()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment