Professional Documents
Culture Documents
Unit05 Hibernate Validator
Unit05 Hibernate Validator
VALIDATION ANNOTATIONS
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
@NotEmpty Checks whether the annotated element is not null nor empty.
ANNOTATION DESCRIPTION
@CreditCardNumber( Checks that the annotated character sequence passes the Luhn checksum test. Note,
ignoreNonDigitCharacters=) this validation aims to check for user mistakes, not credit card validity!
Checks that the annotated character sequence is a valid EAN barcode. The default is
@EAN
EAN-13.
@Length(min=, max=) Validates that the annotated character sequence is between min and max included.
Checks whether the annotated value lies between (inclusive) the specified minimum
@Range(min=, max=)
and maximum.
@UniqueElements Checks that the annotated collection only contains unique elements.
@URL Checks if the annotated character sequence is a valid URL according to RFC2396.
@Email(message = "{user.email.invalid}")
@NotEmpty(message = "Please enter email")
private String email;
ValidationMessages.properties
user.name.invalid=Invalid Username
user.email.invalid=Invalid Email
// Validate bean
Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
// Show errors
if (constraintViolations.size() > 0) {
for (ConstraintViolation<User> violation : constraintViolations) {
System.out.println(violation.getMessage());
}
} else {
System.out.println("Valid Object");
}
}
}
VALIDATING RANGES
@DurationMin(days = 1, hours = 2)
@DurationMax(days = 2, hours = 1)
private Duration duration;
VALIDATING STRINGS
URL AND HTML VALIDATION
@Length(min = 1, max = 3)
private String someString;
@CodePointLength(min = 1, max = 3)
private String someString;
@ISBN
private String someString; // ex: 978-161-729-045-9
@URL(protocol = "https")
private String url;
§ We can also verify that a property contains “safe” HTML code (for
example, without script tags)
@SafeHtml
private String html;