Pregunta

I want create a custom annotation to validate an attribute in my ManagedBean for exemple @StartWithUpperCase

public @interface StartWithUpperCase{
    // 
}

and im manegedBean class i use my annotation like :

public class myBean implements java.io.Serializable{
  @StartWithUpperCase
  @NotNull
  private name;
}

how I can do it.

¿Fue útil?

Solución 2

Start by placing the @Constraint annotation on your custom validation annotation class. As you can see in the javadoc, @Constraint requires a validation implementation class which implements ConstraintValidator.

Your custom annotation class is required to have:

  • a String message() property
  • a Class<?>[] groups() default {} property
  • a Class<? extends Payload>[] payload() default {} property

It can have other properties specific to your validation implementation if you wish.

If you want your annotation's message(s) to be localizable, the Bean Validation framework supports internationalized messages by looking for a ResourceBundle whose fully qualified name is "ValidationMessages". A constraint annotation's properties can make use of that ResourceBundle by including ResourceBundle keys in braces, such as String message() default "{StartWithUpperCase_message}";.

Otros consejos

You can implement it without annotations using a custom validator with jsf, but since jsf 2.0 you can use bean validations and you can create custom constrains with annotations, I found a very good example that does what you need.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top