'Is this a bad way to handle a String DateTime Constraint?
I created my own custom annotation. It basically tries to parse a String into LocalDateTime while following a custom pattern.
Here is the annotation:
@Documented
@Constraint(validatedBy = ValidateDateStringImpl.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateDateString {
String message() default "Invalid date-time format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Here is the Validation Logic:
@Slf4j
public class ValidateDateStringImpl implements ConstraintValidator<ValidateDateString, String> {
private DateTimeFormatter dateTimeFormatter;
@Override
public void initialize(ValidateDateString constraintAnnotation) {
dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSz");
}
@Override
public boolean isValid(String dateString, ConstraintValidatorContext context) {
try{
LocalDateTime.parse(dateString,dateTimeFormatter);
}
catch (DateTimeParseException ex){
log.info(String.valueOf(ex));
return false;
}
return true;
}
}
Here is where the annotation is being used:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Foo{
@NotBlank
@ValidateDateString
private String fooDateTime;
}
Is this a good approach, or are there some better alternatives. Thanks in advance!
Solution 1:[1]
I would expect
def do_something
self.class.helper_methods
end
to return the value from the class variable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | spickermann |
