Constraint class abstract
The base class of every validation rule written as an annotation, such
as @NotBlank() or @Min(18), and the class to extend for your own.
A constraint is a const object put on a property of an @Introspected
class, on the class itself (to compare properties), or on a method
parameter or method of a @Validated() bean. The validator calls
isValid (through isValidWithContext) with the value; when it
returns false it reports a violation with name as error code and
message (or defaultMessage) as text.
Write a subclass for a rule the built-in constraints do not cover, so
it can be reused as an annotation and its errors get message codes like
the others. Like Jakarta's, most constraints accept null; add
NotNull to require a value.
// A class-level constraint comparing two properties.
class PasswordsMatch extends Constraint {
const PasswordsMatch({super.message});
@override
String get name => 'PasswordsMatch';
@override
String get defaultMessage => 'passwords must match';
@override
bool isValid(Object? value) =>
value is! SignupForm || value.password == value.confirm;
}
@Introspected()
@PasswordsMatch()
class SignupForm {
String password = '';
String confirm = '';
}
Spring (Java):
@Constraint(validatedBy = PasswordsMatchValidator.class)
@Target(TYPE) @Retention(RUNTIME)
public @interface PasswordsMatch {
String message() default "passwords must match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
class PasswordsMatchValidator
implements ConstraintValidator<PasswordsMatch, SignupForm> {
public boolean isValid(SignupForm f, ConstraintValidatorContext c) {
return f == null || f.getPassword().equals(f.getConfirm());
}
}
Constructors
-
Constraint({String? message, List<
Type> groups = const []}) -
A constraint with an optional custom
messageand thegroupsit belongs to (none: Default).const
Properties
-
attributes
→ Map<
String, Object?> -
The settings of the constraint by name, such as
{'max': 20, 'min': 0}: they fill the{max}placeholders of messages and, sorted by name, become the arguments{1},{2}, ... of field errors. Empty by default; override it when a custom constraint has settings.no setter - defaultMessage → String
-
The text of a violation when message is not set, with the same
placeholders, such as
size must be between {min} and {max}.no setter -
groups
→ List<
Type> -
The validation groups the constraint belongs to, such as
[OnUpdate]; it is only checked when one of them is asked for. Empty means Default.final - hashCode → int
-
The hash code for this object.
no setterinherited
- message → String?
-
The text of a violation instead of defaultMessage;
nullkeeps the default.final - name → String
-
The error code of a violation, such as
NotBlank: the start of the message codes (NotBlank.signup.name, ...,NotBlank) and the Jakarta name of the constraint. Custom constraints usually return their class name.no setter - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
appliesTo(
List< Type> requested) → bool -
Whether the constraint is checked when a validation asks for the
requestedgroups: when one of its groups is requested. -
checkParameters(
) → void -
Throws a ConstraintDeclarationException when the constraint's own
settings are invalid:
Size(min: -1),min > max, a malformed regular expression. Does nothing by default. -
interpolate(
String template) → String -
templatewith its{attribute}placeholders replaced by the values of attributes; other placeholders and${...}expressions stay, and the escapes\{,\},\$,\\become the literal characters. -
interpolatedMessage(
) → String -
message, or defaultMessage, with the
{attribute}placeholders filled in; message keys and${...}expressions stay, since only the validator can resolve them. -
isValid(
Object? value) → bool -
Whether
valuesatisfies the constraint; the method a custom constraint implements. -
isValidWithContext(
Object? value, ConstraintValidatorContext context) → bool -
Whether
valuesatisfies the constraint, with access to the validationcontext; the methodBeanValidatorcalls. By default it returns isValid. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
supports(
Object value) → bool -
Whether the constraint can check a value of this type at all;
valueis nevernull.@Sizesupports strings, collections and maps, not anint. -
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited