JSR 303 Validation for Dates

A common case is to validate date inputs in Java e.g. to avoid the nice and friendly typos like 06/01/1500.

Nevertheless by default where is not to much support to handle this very common case. So let’s fix this together:

Annotation first

The first we need is a JSR annotation which we use to annotate the code. We provide from the start proper default values, to avoid none sense data.

Validator next

As we have the annotation now, we still need to add some code behind for the JSR bean validation to make it really do something. I assume that both classes are in the same package.

The validator is not very smart now, but it will do the job for. Let’s use it first, will we?

Note: This tutorial is a bit old, use nowadays the DateTimeFormatter from the Java time.

Apply our date validation

Well not to surprising but the interesting part is of course always the test case we should add to verify all is good and working as we like it.

i18n File

Assuming you use a default maven project we should add in /src/main/resources the file ValidationMessages.properties if it not already exists:

Note: You can use placeholders in the messages string. Here we use min and max, which automatically add the values from our annotation into the user message.

Going further

  • Well as you noticed right now we parse the min and max date each time. We could of course just do this once as it is quite static
  • We use currently java.util.Date well again something we could change
  • Last but not least we should try to avoid Date in the API / Model objects and try to just use simply UTC Longs

Paul Sterl has written 20 articles

2 thoughts on “JSR 303 Validation for Dates

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">