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.
- 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.
- 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.
- To create validation.xml, click in WebSphere® Developer Tools.
To create new constraint mappings, complete the following steps. - Double-click the validation.xml file to open it in the Bean
Validation configuration editor.
- Select Validation Configuration and then click
Add.
- Select Constraint Mapping and then click OK.
- To open the Create constraints declaration file wizard, click
Reference in the Details section.
- 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.
- Use a deployment descriptor editor to configure and declare validation constraints that are
used in your application logic.