JavaBean Validation - Creating custom constraint annotation

[Updated: Aug 18, 2017, Created: Sep 23, 2016]

JavaBean validation specifications provides ways to hook up custom annotations to the framework.

In cases where predefined constraints are not sufficient, we can easily create custom constraints for our specific validation requirements.

We have to follow these steps to create a custom constraint:

Creating the custom annotation

In this example, we are going to validate a string for a valid language name.

The new annotation must be annotated with @Constraint specifying a custom validator class for it's element 'validatedBy'. This validator class should implement ConstraintValidator interface.

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
    @Constraint(validatedBy = LanguageValidator.class)
    public @interface Language {
        String message () default "must be a valid language." +
                                   "Found: ${validatedValue}";

        Class<?>[] groups () default {};

        Class<? extends Payload>[] payload () default {};

Creating the validator:

We need to implement the interface ConstraintValidator<A extends Annotation,T>. The implementation code defines the logic to validate a given constraint of type A used on a given field/property type T. In our case our constraint is 'Language' and the given type where we are going to use @Language is java.lang.String.

    public class LanguageValidator implements ConstraintValidator<Language, String> {

        public void initialize (Language constraintAnnotation) {

        public boolean isValid (String value, ConstraintValidatorContext context) {
            if (value == null) {
                return false;
            for (Locale locale : Locale.getAvailableLocales()) {
                if (locale.getDisplayLanguage().equalsIgnoreCase(value)) {
                    return true;

            return false;

What is ConstraintValidatorContext?

As saw in above example, ConstraintValidatorContext provides contextual data and performs operation to customize validation constraints.

The bean:

This is the bean where we are going to use the new annotation.

    public class TestBean {
        private String language;

        public String getLanguage () {
            return language;

        public void setLanguage (String language) {
            this.language = language;


    TestBean testBean = new TestBean();
language must be a valid language display name. found: englis

Example project

Dependencies and Technologies Used:

  • Hibernate Validator Engine 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation.
  • Expression Language API 2.2 2.2.4
  • Expression Language 2.2 Implementation 2.2.4
  • JDK 1.8
  • Maven 3.0.4

Custom Constraint Annotation Select All Download
  • validation-custom-constraint
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also