Thursday, March 24, 2016

JSF 2.2 Tip of the Day: Using Hibernate Validators with JSF

Introduction

Hibernate validators offer a plethora of validators to make your development work much easier. Some of the common ones that are used are @NotNull, @NotBlank, and @NotEmpty. To take advantage of these validators, and avoid some misconceptions, a little information needs to be provided.

@NotNull

Everyone likes this particular annotation, and it can be a real life saver. However something that often catches developers using it on JSF is that JSF treats empty form fields as empty strings. This is not the same as null. So if you want JSF to capture these values and treat them as null values, you need to tell JSF to do so. This is accomplished by adding the following context parameter to the web.xml file.
    <context-param>
         <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
         <param-value>true</param-value>
    </context-param>
Once this is added to the context, all blanks will be treated as null values. Be mindful of any side effects created from this change.

@NotEmpty

This validator causes a lot of confusion. The value can not be null, but can be any character including whitespace, e.g. You can enter a space, and it will accept it.

@NotEmpty

This is the most useful annotation from my standpoint. This makes sure that the input is not null, and is not an empty string like white spaces. This is really what I think most developers are really after anyway. They want to make sure that users fill in form fields.

Code

The code for this project can be found on Github, and includes some additional bonus code such as using locales, and custom messages. The code can be found here: jsf-hibernate-validator.


0 comments :

Popular Posts