BeanValidator class
The validator: it checks an object against the constraint annotations
on its class (@NotBlank(), @Min(18), custom Constraints) and
reports what is broken.
Spring Boot registers one as the defaultValidator bean, with the
context's introspector, and uses it for @Valid() request bodies and
@Validated() beans (@ConfigurationProperties classes get a plain
validator of their own). Inject it
(BeanValidator or Validator) when you check an object yourself:
a batch import, a message from a queue, data that does not come
through a controller. Declare your own BeanValidator bean to set a
validationMessageSource, a clockProvider or groupSequences; Boot
then backs off. The class must be @Introspected (the generator
describes its properties); other objects are not checked.
It answers in two forms:
- As a Validator, it records errors in an Errors: each violation
becomes a
FieldErrorwith the constraint's name as code (NotBlank.signup.name, ...,NotBlank), somessages.propertiescan word it. The arguments follow Spring:{0}is the field, then the constraint's attributes sorted by name ({1}is the limit of@Min); string attributes come as ResolvableAttributes. A field that already has a binding failure (typeMismatch) gets no constraint error on top. - validateObject and its siblings return ConstraintViolations with finished messages.
Messages are interpolated as in Jakarta Bean Validation: {key}
placeholders are looked up in validationMessageSource, repeatedly
while the result has placeholders; the built-in messages are also
available under jakarta.validation.constraints.<Name>.message, with
Hibernate's English defaults when no message source defines them. Then
{attribute} placeholders take the constraint's attributes, and
${validatedValue} the invalid value; \{, \}, \$ and \\
stay literal characters. Date constraints read "now" from
clockProvider.
@Introspected()
class SignupForm {
@NotBlank()
@Size(max: 20)
String name = '';
@Min(18)
int age = 0;
}
// A 17-year-old signs up: the form binds, but @Min(18) fails.
final form = SignupForm();
final binder = DataBinder(form, objectName: 'signup')
..validators.add(validator) // the injected BeanValidator
..bind({'name': 'Ada', 'age': '17'})
..validate();
final error = binder.bindingResult.fieldError('age')!;
error.defaultMessage; // 'must be greater than or equal to 18'
// With `Min={0} must be at least {1}` in messages.properties, the
// application's message source words it: 'age must be at least 18'.
messageSource.getMessageFromResolvable(error);
Spring (Java):
class SignupForm {
@NotBlank @Size(max = 20) private String name;
@Min(18) private int age;
}
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
DataBinder binder = new DataBinder(form, "signup");
binder.setValidator(validator);
binder.bind(new MutablePropertyValues(Map.of("name", "Ada", "age", "17")));
binder.validate();
- Implemented types
Constructors
-
BeanValidator({BeanIntrospector? introspector, MessageSource? validationMessageSource, ClockProvider clockProvider = const DefaultClockProvider(), Map<
Type, List< groupSequences = const {}})Type> > -
A validator that reads the constraints through
introspector, by defaultBeanIntrospector.shared; inside an application pass the context'sBeanIntrospector, which knows the application's classes.
Properties
- clockProvider → ClockProvider
-
Gives "now" to
@Past,@FutureDateand the other date constraints; replace it in tests to fix the date.final -
groupSequences
→ Map<
Type, List< Type> > -
The group sequences: each key group stands for the listed groups,
checked in order until one has a violation. Empty by default.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- introspector → BeanIntrospector
-
Describes the classes: where the constraints are and how to read the
property values.
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- validationMessageSource → MessageSource?
-
Resolves
{key}placeholders in constraint messages, such as@NotBlank(message: '{signup.name.missing}'), and may replace a built-in message underjakarta.validation.constraints.<Name>.message.null(the default, also for Boot'sdefaultValidator) leaves unknown keys as they are.final
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
supports(
Object target) → bool -
Whether this validator knows how to check
target; usually a type test such astarget is SignupForm.override -
toString(
) → String -
A string representation of this object.
inherited
-
validate(
Object target, Errors errors) → void -
Checks
targetand records every problem inerrors, with Errors.rejectValue for a field or Errors.reject for the whole object. Records nothing whentargetis valid; does not throw for invalid data.override -
validateObject(
Object target, {List< Type> groups = const []}) → List<ConstraintViolation> -
Every violation of
target, including those inside@Valid()properties; an empty list when it is valid or not@Introspected. -
validateParameters(
Object target, MethodSignature method, List< Object?> arguments, {List<Type> groups = const []}) → List<ConstraintViolation> -
The violations of the
argumentsof a call tomethodoftarget: the constraints on each parameter, and those inside@Valid()arguments. Paths aremethod.parameter(register.email,save.order.items[0].sku). Jakarta'sExecutableValidator.validateParameters. -
validateProperty(
Object target, String property, {List< Type> groups = const []}) → List<ConstraintViolation> -
The violations of the single
propertyoftarget, without going into@Valid()values; useful to check one form field as the user leaves it. Jakarta'svalidateProperty. -
validateReturnValue(
Object target, MethodSignature method, Object? returnValue, {List< Type> groups = const []}) → List<ConstraintViolation> -
The violations of the
returnValueofmethod: the constraints on the method and, with@Valid()on it, those inside the returned object. Paths start withmethod.<return value>. Jakarta'sExecutableValidator.validateReturnValue. -
validateValue(
Type type, String property, Object? value, {List< Type> groups = const []}) → List<ConstraintViolation> -
The violations
valuewould cause aspropertyof the classtype, without an instance; useful to check input before creating the object. Jakarta'svalidateValue. -
validateWithGroups(
Object target, Errors errors, List< Type> groups) → void -
Checks
targetagainst the constraints ofgroupsonly and records the problems inerrors.override
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited