JSF/Hibernate NotBlank validation

2020-05-06 13:56发布

问题:

I have a simple JSF+RichFaces form with some fields and obviously a backing bean to store them. In that bean all the necessary properties have validation annotations (jsr303/hibernate), but I can't seem to find an annotation which would check if the property (String) is blank. I know there's a @NotBlank annotation in spring modules, but JSF doesn't support spring validation. Is there any easy way to check it or should I write my own annotation?

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

回答1:

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.



回答2:

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.



回答3:

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]*$)").