Red Hat Training

A Red Hat training course is available for Red Hat JBoss Enterprise Application Platform

13.6. Bean Validation

13.6.1. About Bean Validation

Bean Validation, or JavaBeans Validation, is a model for validating data in Java objects. The model uses built-in and custom annotation constraints to ensure the integrity of application data. The specification is documented here: http://jcp.org/en/jsr/detail?id=303.
Hibernate Validator is the JBoss EAP 6 implementation of Bean Validation. It is also the reference implementation of the JSR.
JBoss EAP 6 is 100% compliant with JSR 303 - Bean Validation. Hibernate Validator also provides additional features to the specification.
To get started with Bean Validation, refer to the bean-validation quickstart example: Section 1.4.1.1, “Access the Quickstarts”.

13.6.2. Hibernate Validator

Hibernate Validator is the reference implementation of JSR 303 - Bean Validation.
Bean Validation provides users with a model for validating Java object data. For more information, refer to Section 13.6.1, “About Bean Validation” and Section 13.6.3.1, “About Validation Constraints”.

13.6.3. Validation Constraints

13.6.3.1. About Validation Constraints

Validation constraints are rules applied to a java element, such as a field, property or bean. A constraint will usually have a set of attributes used to set its limits. There are predefined constraints, and custom ones can be created. Each constraint is expressed in the form of an annotation.
The built-in validation constraints for Hibernate Validator are listed here: Section 13.6.3.3, “Hibernate Validator Constraints”

13.6.3.2. Create a Constraint Annotation in Red Hat JBoss Developer Studio

Summary

This task covers the process of creating a constraint annotation in Red Hat JBoss Developer Studio, for use within a Java application.

Procedure 13.5. Create a Constraint Annotation

  1. Open a Java project in Red Hat JBoss Developer Studio.
  2. Create a Data Set

    A constraint annotation requires a data set that defines the acceptable values.
    1. Right click on the project root folder in the Project Explorer panel.
    2. Select NewEnum.
    3. Configure the following elements:
      • Package:
      • Name:
    4. Click the Add... button to add any required interfaces.
    5. Click Finish to create the file.
    6. Add a set of values to the data set and click Save.

    Example 13.25. Example Data Set

    package com.example;
    
    public enum CaseMode {
        UPPER,
        LOWER;
    }
    
  3. Create the Annotation File

    Create a new Java class.
  4. Configure the constraint annotation and click Save.

    Example 13.26. Example Constraint Annotation File

    package com.mycompany;
    
    import static java.lang.annotation.ElementType.*;
    import static java.lang.annotation.RetentionPolicy.*;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    import javax.validation.Constraint;
    import javax.validation.Payload;
    
    @Target( { METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = CheckCaseValidator.class)
    @Documented
    public @interface CheckCase {
    
        String message() default "{com.mycompany.constraints.checkcase}";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
        
        CaseMode value();
    
    }
Result
A custom constraint annotation with a set of possible values has been created, ready to be used in the Java project.

13.6.3.3. Hibernate Validator Constraints

Table 13.11. Built-in Constraints

Annotation Apply on Runtime checking Hibernate Metadata impact
@Length(min=, max=) property (String) Check if the string length matches the range. Column length will be set to max.
@Max(value=) property (numeric or string representation of a numeric) Check if the value is less than or equal to max. Add a check constraint on the column.
@Min(value=) property (numeric or string representation of a numeric) Check if the value is more than or equal to Min. Add a check constraint on the column.
@NotNull property Check if the value is not null. Column(s) are not null.
@NotEmpty property Check if the string is not null nor empty. Check if the connection is not null nor empty. Column(s) are not null (for String).
@Past property (date or calendar) Check if the date is in the past. Add a check constraint on the column.
@Future property (date or calendar) Check if the date is in the future. None.
@Pattern(regex="regexp", flag=) or @Patterns( {@Pattern(...)} ) property (string) Check if the property matches the regular expression given a match flag (see java.util.regex.Pattern). None.
@Range(min=, max=) property (numeric or string representation of a numeric) Check if the value is between min and max (included). Add a check constraint on the column.
@Size(min=, max=) property (array, collection, map) Check if the element size is between min and max (included). None.
@AssertFalse property Check that the method evaluates to false (useful for constraints expressed in code rather than annotations). None.
@AssertTrue property Check that the method evaluates to true (useful for constraints expressed in code rather than annotations). None.
@Valid property (object) Perform validation recursively on the associated object. If the object is a Collection or an array, the elements are validated recursively. If the object is a Map, the value elements are validated recursively. None.
@Email property (String) Check whether the string is conform to the e-mail address specification. None.
@CreditCardNumber property (String) Check whether the string is a well formatted credit card number (derivative of the Luhn algorithm). None.
@Digits(integerDigits=1) property (numeric or string representation of a numeric) Check whether the property is a number having up to integerDigits integer digits and fractionalDigits fractional digits. Define column precision and scale.
@EAN property (string) Check whether the string is a properly formatted EAN or UPC-A code. None.

13.6.4. Configuration

13.6.4.1. Example Validation Configuration File

Example 13.27. validation.xml

<validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration">

    <default-provider>
        org.hibernate.validator.HibernateValidator
    </default-provider>
    <message-interpolator>
        org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator
    </message-interpolator>
    <constraint-validator-factory>
        org.hibernate.validator.engine.ConstraintValidatorFactoryImpl
    </constraint-validator-factory>
    
    <constraint-mapping>
        /constraints-example.xml
    </constraint-mapping>
    
    <property name="prop1">value1</property>
    <property name="prop2">value2</property>
</validation-config>