I have a Java EE application and I want to validate a Date. With a String I do this:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
...
@NotNull
@Size(min = 1, max = 255)
private String myString;
But now I have two dates which I want to validate. The user can in the frontend system write a String in a text field which will be transferred via JSON (I have to use text field, I can not use a datepicker).
So my backend does have this in my domain class:
@DateTimeFormat(pattern = "dd.MM.yy")
@Temporal(value=TemporalType.TIMESTAMP)
private Date myStartDate;
@DateTimeFormat(pattern = "dd.MM.yy")
@Temporal(value=TemporalType.TIMESTAMP)
private Date myEndDate;
I want to validate against the format "dd.MM.yyyy". How can this be done?
And, I do not think so, but is there an automatic validation to check if the start date is before the end date? I only found @Future
and @Past
.
So the only solution is to use a @Pattern, a regular expression?!
Thank you in advance for your help, Best Regards.
1 Overview of the JSR-303 Bean Validation API. JSR-303 standardizes validation constraint declaration and metadata for the Java platform. Using this API, you annotate domain model properties with declarative validation constraints and the runtime enforces them.
This value must be in the past and must follow a specific pattern (dd-mm-yyyy). Any date value violating these constraints should result in a validation error. We will use @Past and @DateTimeFormat to validate the date field.
validation will validate the nested object for constraints with the help of javax. validation implementation provider, for example, hibernate validator. @Valid also works for collection-typed fields. In the case of collection-typed fields, each collection element will be validated.
@DateTimeFormat is used during web data binding, when mapping request parameters onto an object (assuming you have enabled it with <mvc:annotation-driven/>
or manually.) It's not generally going to be used when deserializing JSON into an object. How are you reading in your JSON? What are you using to deserialize it? You can't validate a java Date object after the fact for the formatting, you have to check up front before deserialization.
There are no multi-field constraints built in. You'll want to write your own type level constraint if you want to compare two properties on an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With