Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate date in the format "MM/dd/yyyy" in Spring Boot?

I need to validate the given date has valid month, date and year. Basically, date format would be MM/dd/yyyy. But date coming like 13/40/2018 then I need to throw an error message like:

invalid start date

Is there any annotation available in spring to get this done?

@NotNull(message = ExceptionConstants.INVALID_START_DATE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
private Date startDate;
like image 455
Saravanan Avatar asked Nov 29 '18 13:11

Saravanan


People also ask

How do you validate a date in Spring boot?

This annotation has an attribute called pattern that allows you to set a the pattern to validate against. Example usage of the annotation: public class PostForm { @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "Please provide a date.") private Date date; private String contents; // getters and setters... }

How do you validate a date in YYYY-MM-DD format in Java?

Validate Using DateFormat Next, let's write the unit test for this class: DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


3 Answers

You can use a custom deserializer :

public class DateDeSerializer extends StdDeserializer<Date> {

    public DateDeSerializer() {
        super(Date.class);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
        String value = p.readValueAs(String.class);
        try {
            return new SimpleDateFormat("MM/dd/yyyy").parse(value);
        } catch (DateTimeParseException e) {
            //throw an error
        }
    }

}

and use like :

@JsonDeserialize(using = DateDeSerializer .class)
 private Date startDate;
like image 139
hasnae Avatar answered Nov 14 '22 20:11

hasnae


You can use something like that:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@JsonFormat(pattern = "MM/dd/yyyy")
private LocalDate startDate;

But I don't know if it can work with class Date

like image 35
veben Avatar answered Nov 14 '22 20:11

veben


@CustomDateValidator
private LocalDate startDate;

@Documented
@Constraint(validatedBy = CustomDateValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDateConstraint {
    String message() default "Invalid date format";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class CustomDateValidator implements
  ConstraintValidator<CustomDateConstraint, LocalDate> {

    private static final String DATE_PATTERN = "MM/dd/yyyy";

    @Override
    public void initialize(CustomDateConstraint customDate) {
    }

    @Override
    public boolean isValid(LocalDate customDateField,
      ConstraintValidatorContext cxt) {
          SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
           try
        {
            sdf.setLenient(false);
            Date d = sdf.parse(customDateField);
            return true;
        }
        catch (ParseException e)
        {
            return false;
        }
    }

}
like image 41
G.Noulas Avatar answered Nov 14 '22 21:11

G.Noulas