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 FieldError with the constraint's name as code (NotBlank.signup.name, ..., NotBlank), so messages.properties can 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<Type>> groupSequences = const {}})
A validator that reads the constraints through introspector, by default BeanIntrospector.shared; inside an application pass the context's BeanIntrospector, which knows the application's classes.

Properties

clockProvider → ClockProvider
Gives "now" to @Past, @FutureDate and 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 under jakarta.validation.constraints.<Name>.message. null (the default, also for Boot's defaultValidator) 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 as target is SignupForm.
override
toString() → String
A string representation of this object.
inherited
validate(Object target, Errors errors) → void
Checks target and records every problem in errors, with Errors.rejectValue for a field or Errors.reject for the whole object. Records nothing when target is 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 arguments of a call to method of target: the constraints on each parameter, and those inside @Valid() arguments. Paths are method.parameter (register.email, save.order.items[0].sku). Jakarta's ExecutableValidator.validateParameters.
validateProperty(Object target, String property, {List<Type> groups = const []}) → List<ConstraintViolation>
The violations of the single property of target, without going into @Valid() values; useful to check one form field as the user leaves it. Jakarta's validateProperty.
validateReturnValue(Object target, MethodSignature method, Object? returnValue, {List<Type> groups = const []}) → List<ConstraintViolation>
The violations of the returnValue of method: the constraints on the method and, with @Valid() on it, those inside the returned object. Paths start with method.<return value>. Jakarta's ExecutableValidator.validateReturnValue.
validateValue(Type type, String property, Object? value, {List<Type> groups = const []}) → List<ConstraintViolation>
The violations value would cause as property of the class type, without an instance; useful to check input before creating the object. Jakarta's validateValue.
validateWithGroups(Object target, Errors errors, List<Type> groups) → void
Checks target against the constraints of groups only and records the problems in errors.
override

Operators

operator ==(Object other) → bool
The equality operator.
inherited