JSF / Hibernate NotBlank Validation

I have a simple JSF + RichFaces form with some fields and obviously bean support for storing them. In this bean, all necessary properties have validation annotations (jsr303 / hibernate), but I cannot find an annotation that will check if the (String) property is empty. I know that spring modules have @NotBlank annotation, but JSF does not support w760 validation. Is there an easy way to verify this or write my own annotation?

@Edit: I already tried @NotNull and @NotEmpty from jsr303 and hibernate, but they both failed, I can still send an empty string like "".

0
source share
3 answers

If you use Hibernate Validator 4.1 as your implementation of JSR-303, they provide the @NotBlank annotation, which is EXACTLY what you are looking for, separate from @NotNull and @NotEmpty. You should use (currently) the latest version, but this will work.

If for some reason you can’t upgrade to the latest version, writing a note is not required.

+9
source

Hibernate Validator 4.1+ provides a custom @NotBlank annotation string that checks for non-null and non-empty after trimming a space. The api doc for @NotBlank states:

The difference from NotEmpty is that trailing spaces are ignored.

If it is not clear that @NotEmpty truncates the string before validation, first look at the description given in document 4.1 under the table 'built -in constaints' :

Make sure that the annotated string is non-zero and the trimmed length is greater than 0. The difference with @NotEmpty is that this restriction can only be applied to strings and that trailing spaces are ignored.

Then review the code and you will see that @NotBlank is defined as :

 @Documented @Constraint(validatedBy=NotBlankValidator.class) @Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER}) @Retention(value=RUNTIME) @NotNull public @interface NotBlank{ /* ommited */ } 

There are two things in this definition. Firstly, the definition of @NotBlank includes @NotNull , so this is an extension of @NotNull . Secondly, it extends @NotNull using @Constraint with NotBlankValidator.class. This class has an isValid method, which:

 public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) { if ( charSequence == null ) { //this is curious return true; } return charSequence.toString().trim().length() > 0; //dat trim } 

Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It is normal that it returns true if it is null, because, as I mentioned, the definition of @NotEmpty @NotNull is also required.

+1
source

Maybe @NotEmpty ?

It is defined as:

 @NotNull @Size(min=1) 

Since you are using richfaces, I assume you are using <rich:beanValidator /> ? It handles JSR 303 annotations.

Update : try (taken from here ):

 @Pattern(regex="(?!^[\s]*$)"). 
0
source

All Articles