JSR annotation-based validation

JSR 303 is a bean specification, which defines the metadata and APIs to validate the beans in J2EE applications. The latest in the market is JSR 349, which is an extension of JSR 303, providing features such as openness, dependency injection, and CDI, method validation, group conversion, and integrations with other specifications. Hibernate Validator is a well-known reference implementation available. The javax.validation.* package provides the APIs for validation purposes.

The following are a few common annotations used in validation:

  • @NotNull: This checks whether the annotated value is not null, but it cannot check for empty strings
  • @Null: This checks whether the annotated value is null
  • @Pattern: This checks whether the annotated string matches the given regular expression or not
  • @Past: This checks whether the annotated value is a date in the past
  • @Future: This checks whether the annotated value is a date in the future
  • @Min: This makes sure that the annotated element is a number whose value is equal to or greater than the specified value
  • @Max: This makes sure that the annotated element is a number whose value is equal to or less than the specified value
  • @AssertFalse: This ensures that the annotated element is false
  • @AssertTrue: This ensures that the annotated element is true
  • @Size: This ensures that the annotated element is between the maximum and minimum values

Apart from the preceding annotations defined by the Bean Validation API, the following additional annotations are provided by Hibernate Validator:

  • @CreditCardNumber: This checks that the annotated value follows the character sequence passed to it
  • @Email: This is used to check whether the specified character follows a valid e-mail address according to the specified expression
  • @Length: This checks whether the annotated element has a number of characters limited by the minimum and maximum attributes specified by the annotation
  • @NotBlank: This checks for the annotated element that is not null, and has a length greater than zero
  • @NotEmpty: This makes sure that the annotated element is neither null nor empty

Let's create a copy of the ReadMyBooks application to implement JSR-based validation by following these steps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.230.82