Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSR 303 - javax.validation - Validate a date

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.

like image 514
Tim Avatar asked Jan 14 '11 19:01

Tim


People also ask

What is JSR 303 Bean Validation?

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.

How do you validate a date in Spring Boot?

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.

How does javax validation valid work?

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.


1 Answers

@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.

like image 107
Affe Avatar answered Sep 29 '22 09:09

Affe