Created
June 15, 2016 07:19
-
-
Save robinraju/875b08694c80836273ebb9b6e5783f77 to your computer and use it in GitHub Desktop.
Java Annotation for validating Date format in the given string
This file contains hidden or 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
import javax.validation.Constraint; | |
import javax.validation.Payload; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.Target; | |
import static java.lang.annotation.ElementType.FIELD; | |
import static java.lang.annotation.ElementType.PARAMETER; | |
import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
/** | |
* Validate that the annotated string is in YYYY/MM/DD Date format | |
*/ | |
@Target({FIELD, PARAMETER}) | |
@Retention(RUNTIME) | |
@Constraint(validatedBy = ValidDateValidator.class) | |
public @interface ValidDate { | |
String message() default "invalid date"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
boolean optional() default false; | |
} |
This file contains hidden or 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
import com.google.common.base.Strings; | |
import javax.validation.ConstraintValidator; | |
import javax.validation.ConstraintValidatorContext; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
public class ValidDateValidator implements ConstraintValidator<ValidDate, String> { | |
private Boolean isOptional; | |
@Override | |
public void initialize(ValidDate validDate) { | |
this.isOptional = validDate.optional(); | |
} | |
@Override | |
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { | |
boolean validDate = isValidFormat("yyyy/MM/dd", value); | |
return isOptional ? (validDate || (Strings.isNullOrEmpty(value))) : validDate; | |
} | |
private static boolean isValidFormat(String format, String value) { | |
Date date = null; | |
try { | |
SimpleDateFormat sdf = new SimpleDateFormat(format); | |
if (value != null){ | |
date = sdf.parse(value); | |
if (!value.equals(sdf.format(date))) { | |
date = null; | |
} | |
} | |
} catch (ParseException ex) { | |
} | |
return date != null; | |
} | |
} |
Thanks man! Help me a lot. ;-)
works flawlessly!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you :)