JSF/Hibernate NotBlank validation

随声附和 提交于 2019-12-02 09:37:56

If you use Hibernate Validator 4.1 as your JSR-303 implementation, they provide a @NotBlank annotation that does EXACTLY what you're looking for, separate from @NotNull and @NotEmpty. You need to be using the (currently) latest version, but that will work.

If you can't go to the latest version for some reason, it doesn't take much to write an annotation yourself.

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

The difference to NotEmpty is that trailing whitespaces are getting ignored.

If this isn't clear that @NotEmpty is trimming the String before the check, first see the description given in the 4.1 document under the table 'built-in constaints':

Check that the annotated string is not null and the trimmed length is greater than 0. The difference to @NotEmpty is that this constraint can only be applied on strings and that trailing whitespaces are ignored.

Then, browse the code and you'll 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 to note in this definition. The first is that the definition of @NotBlank includes @NotNull, so it's an extension of @NotNull. The second is that it extends @NotNull by using an @Constraint with NotBlankValidator.class. This class has an isValid method which is:

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's ok that it returns true if it's null because, as I mentioned, the @NotEmpty definition also requires @NotNull.

Perhaps @NotEmpty ?

Which is defined as:

@NotNull
@Size(min=1)

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

Update: Try (taken from here):

@Pattern(regex="(?!^[\s]*$)"). 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!