Binders withValidator - can one pass info from predicate to errorMessagePro

A question re. the Binder’s withValidator(...) method (...Binder.BindingBuilder.withValidator(SerializablePredicate<? super String> predicate, ErrorMessageProvider errorMessageProvider):

I have several cases where - when a validation fails - I would like to include some details about why it failed to the error message.
In other words: it would be great to be able to pass some object or String from the execution of the predicate to the errorMessageProvider. Is that possible?

E.g. what is the ErrorMessageProvider’s “context” parameter there for? Can one add something to this context from the predicate?

If you use the validator version, withValidator(Validator<? super TARGET> validator), you’ll have more control over the message:

binder.forField(textField).withValidator((value, context) -> {
	if (value.startsWith("A")) {
		return ValidationResult.error("Name can't start with A");
	} else if (value.startsWith("B")) {
		return ValidationResult.error("Name can't start with B");
	}
	return ValidationResult.ok();
}).bind(...);

If you want a separate error message provider, you could plug in a custom solution in the validator, one that does not necessarily implement ErrorMessageProvider:

if (value.startsWith("A")) {
    return ValidationResult.error(myErrorMessageProvider.get(MyErrorEnum.INCORRECT_STRING));
}

The ValueContext is primarly used to get the locale for conversions and error messages.

Michael Moser:
A question re. the Binder’s withValidator(...) method (...Binder.BindingBuilder.withValidator(SerializablePredicate<? super String> predicate, ErrorMessageProvider errorMessageProvider):

I have several cases where - when a validation fails - I would like to include some details about why it failed to the error message.
In other words: it would be great to be able to pass some object or String from the execution of the predicate to the errorMessageProvider. Is that possible?

E.g. what is the ErrorMessageProvider’s “context” parameter there for? Can one add something to this context from the predicate?

I had a similat issue and ended up writing my own StringLengthValidator. I pass it validation criteria (e.g. min 10 max 55) and based on that it can generate better messages such as

“name has to be at least 10 charaters long”
“name cannot be longer than 55 characters”

Great hints! Thanks to both!