Configuring Bean Validation

You can use Bean Validation to use one or more constraints to verify data that is used in application logic. You can use predefined constraints, or you can create your own.

Before you begin

Choose the top-level feature Web Development Tools to automatically include the Bean Validation tools.

About this task

Use constraint annotation or XML deployment descriptor files to configure Bean Validation and describe custom constraint declarations.

Procedure

  • Configure Bean Validation with constraint annotations. On Web 4.0 projects, Bean Validation 2.0 is used.
    1. Choose a predefined constraint annotation, or use the meta-annotation @Constraint to create a custom constraint and use it in application logic.
      The Interface ConstraintValidator must be implemented if you want to use it as a custom constraint class.
      Important: There are 13 predefined constraint annotations, all in the package javax.validation.constraints: @AssertFalse, @AssertTrue, @DecimalMax, @DecimalMin, @Digits, @Future, @Max, @Min, @NotNull, @Null, @Past, @Pattern, and @Size.
      Note: Bean Validation 2.0, or higher includes the annotations, @Email, @NotEmpty, @NotBlank, @Positive, @PositiveOrZero, @Negative, @NegativeOrZero, @PastOrPresent, @FutureOrPresent.
    2. Use your chosen annotation before the field declaration to verify data that is used in application logic.
      For example, method variables can be validated to be not null by using the predefined annotation @NotNull before the variable declaration.
      Validation can be used on fields, method parameters, and at a class level to check more than one data point at a time.
  • Configure Bean Validation with XML deployment descriptor files.
    1. To create a validation.xml file, click Java EE Tools > Create Bean Validation configuration file in WebSphere® Developer Tools.
    2. To create new constraint mappings, complete the following steps.
      1. Double-click the validation.xml file to open it in the Bean Validation configuration editor.
      2. Select Validation Configuration and then click Add.
      3. Select Constraint Mapping and then click OK.
      4. To open the Create constraints declaration file wizard, click Reference in the Details section.
      5. Click Finish.

      The constraint mappings are declared in the validation.xml file by the <constraint-mapping> tag. The constraint mapping files do not follow a naming formula. They are automatically placed in the META-IF/validation directory of the archive.

    3. Use a deployment descriptor editor to configure and declare validation constraints that are used in your application logic.