Built-in Constraints

YAVI provides built-in constraints for each supported type. The same constraint object is used by the schema style and by the classic style, so each constraint is documented once on this page.

The following program applies email(), ip() and multipleOf(3) and prints the violation for each invalid value.

import am.ik.yavi.builder.ValidatorBuilder;
import am.ik.yavi.core.Validator;
import am.ik.yavi.validator.Yavi;

// Schema style: the validator of a single value
var emailValidator = Yavi._string("email", c -> c.notBlank().email());

// Classic style: a property of an object
record Signup(String email) {}

Validator<Signup> signupValidator = ValidatorBuilder.<Signup>of()
        ._string(Signup::email, "email", c -> c.notBlank().email())
        .build();

The lambdas are identical. In the schema style, a property is also written with Yavi.schema()._string("email", c -> ...); in the classic style, the typed method _string selects the type of the property and avoids an ambiguous inference, and constraint is the untyped alternative.

Null values and required values

The schema style and the classic style differ in what null means.

  • A property of Yavi.schema() and a validator of a single value built with Yavi._string(...) reject null by default with object.notNull. A value that may be null declares it with nullable() (or optional(), defaultValue(...), recover(...)); see Optional and Default Values. isNull() is usable only after nullable().
  • A property of a ValidatorBuilder validator is valid when it is null, and every check is skipped, unless a constraint rejects null. notNull(), notBlank() and notEmpty() reject null; the other constraints on this page do not.
  • An empty string is valid for every format of a string, whatever the style. A format tells what a given text looks like, not that a text is given. Add notEmpty() or notBlank() to require it.

The message key and the params names of each constraint are listed with it. params of a violation holds the arguments by name and does not include the name of the value or the violated value; the positional arguments remain available from ConstraintViolation#args(). See Violations.

String and CharSequence

Use _string for a String; the classic style also has _charSequence for a CharSequence. The constraints are in am.ik.yavi.constraint.CharSequenceConstraint.

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
Not emptynotEmpty()non-null, not emptycontainer.notEmpty-
Not blanknotBlank()non-null, not only white spacecharSequence.notBlank-
Fixed sizefixedSize(int)the given number of characterscontainer.fixedSizesize, actualSize
Size greater thangreaterThan(int)more than the given numbercontainer.greaterThanmin, actualSize
Size greater than or equalgreaterThanOrEqual(int)at least the given numbercontainer.greaterThanOrEqualmin, actualSize
Size less thanlessThan(int)fewer than the given numbercontainer.lessThanmax, actualSize
Size less than or equallessThanOrEqual(int)at most the given numbercontainer.lessThanOrEqualmax, actualSize
Containscontains(CharSequence)text containing the sequencecharSequence.containssubstring
Starts withstartsWith(CharSequence)text starting with the prefixcharSequence.startsWithprefix
Ends withendsWith(CharSequence)text ending with the suffixcharSequence.endsWithsuffix
Patternpattern(String), pattern(Pattern), pattern(Supplier<Pattern>)text matching the regular expressioncharSequence.patternpattern
Emailemail()an email addresscharSequence.email-
UUIDuuid()8-4-4-4-12 hexadecimal; version and variant are not checkedcharSequence.uuid-
ULIDulid()26 characters of Crockford Base32, first 0-7, upper or lower casecharSequence.ulid-
IP addressip()an IPv4 or IPv6 addresscharSequence.ip-
IPv4ipv4()an IPv4 addresscharSequence.ipv4-
IPv6ipv6()an IPv6 address, including a zone id and a prefix lengthcharSequence.ipv6-
URIuri()an absolute URI with a scheme of any kind (mailto:, urn:, s3://); a character outside US-ASCII is rejectedcharSequence.uri-
URLurl()a URL that java.net.URI parsescharSequence.url-
URL with restrictionsurl(url -> url.protocol(...).host(...).port(...).build())a valid URL whose protocol, host and port are in the given setscharSequence.url, charSequence.url.protocol, charSequence.url.host, charSequence.url.portvalues
Luhnluhn()decimal digits that pass the Luhn checksumcharSequence.luhn-
Password policypassword(policy -> ...)text that meets the policiespassword.required, password.optionalpolicy / min, policies
Byte representationisByte()text that parses as a BytecharSequence.byte-
Short representationisShort()text that parses as a ShortcharSequence.short-
Integer representationisInteger()text that parses as an IntegercharSequence.integer-
Long representationisLong()text that parses as a LongcharSequence.long-
Float representationisFloat()text that parses as a FloatcharSequence.float-
Double representationisDouble()text that parses as a DoublecharSequence.double-
BigInteger representationisBigInteger()text that parses as a BigIntegercharSequence.biginteger-
BigDecimal representationisBigDecimal()text that parses as a BigDecimalcharSequence.bigdecimal-
Local dateisoLocalDate(), localDate(String pattern)a date in the pattern, resolved with ResolverStyle.STRICTcharSequence.localdatepattern

ip(), uri() and ulid() are new in 0.18. url(builder) restricts the parsed URL: protocol accepts protocol names, host accepts host names compared case-insensitively as written, and port accepts port numbers; a URL without an explicit port is matched against the default port of its protocol.

var proxyValidator = Yavi._string("proxy", c -> c.notBlank().ip());
proxyValidator.validate("");                 // "proxy" must not be blank
proxyValidator.validate("192.0.2.1");        // Valid
proxyValidator.validate("2001:db8::1");      // Valid
proxyValidator.validate("example.com");      // Invalid (charSequence.ip)

var homepageValidator = Yavi._string("homepage", c -> c.uri());
homepageValidator.validate("mailto:a@example.com"); // Valid
homepageValidator.validate("/relative/path");       // Invalid

pattern(Supplier<Pattern>) calls the supplier for every validation, for regular expressions that are built at validation time.

Built-in password policies are UPPERCASE, LOWERCASE, ALPHABETS, NUMBERS and SYMBOLS in am.ik.yavi.constraint.password.PasswordPolicy. A policy is required with required(...) or made one of a minimum count with optional(int, ...); uppercase(2) requires two upper case characters. A custom PasswordPolicy can be passed in the same way.

Character counting and byte size

The size constraints of a character sequence count Unicode code points after normalization and after the ignored variation selectors are removed. The default normalizer is Normalizer.Form.NFC, so モジ written as モシ plus a voiced sound mark counts as two characters instead of three. The constraints that inspect the text itself (contains, startsWith, endsWith, pattern, the formats and codePoints) do not normalize the value.

ConstraintMethodEffectMessage keyparams
Normalizernormalizer(Normalizer.Form), normalizer(null)sets or disables the normalization applied before the size is measured--
Emojiemoji()counts emoji sequences as one character, using extended grapheme clusters; it is off by default--
Variant selectorsvariant(opts -> opts.ivs(...).svs(...).fvs(...))removes the selected variation selectors before the size is measured--
Code pointscodePoints(...).asWhiteList(), .asBlackList()allows or forbids the given code pointscodePoints.asWhiteList, codePoints.asBlackListnotAllowed
Byte sizeasByteArray(), asByteArray(Charset) followed by fixedSize, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqualmeasures the encoded byte lengthbyteSize.fixedSize, byteSize.greaterThan, byteSize.greaterThanOrEqual, byteSize.lessThan, byteSize.lessThanOrEqualsize, actualSize / min, actualSize / max, actualSize

emoji() is not enabled by default because it is expensive. In 0.18 it counts extended grapheme clusters, so "\r\n" and a half-width katakana with a voiced sound mark count as one; the Emoji class is removed.

normalizer, emoji() and variant(...) are not constraints by themselves: the message of the size constraint applied to their result is reported. Code point sets are represented by am.ik.yavi.constraint.charsequence.CodePoints, and built-in sets are available from AsciiCodePoints and UnicodeCodePoints.

An emoji sequence is counted as one only when emoji() is added; otherwise each code point is counted. asByteArray() measures the UTF-8 byte length unless a charset is given, for a column whose byte length is limited.

var messageValidator = Yavi._string("text", c -> c.emoji().lessThanOrEqual(3)
        .asByteArray().lessThanOrEqual(16));
messageValidator.validate("I❤️☕️️");        // Valid
messageValidator.validate("❤️❤️❤️️️");     // Invalid (byteSize.lessThanOrEqual)

Integral numbers

The classic style uses _byte, _short, _integer, _long, _character and _bigInteger for the corresponding types; the schema style has _short, _integer, _long and _bigInteger. The constraints on Character compare the numeric value of the character; the zero value used by positive and the other sign constraints is Character.MIN_VALUE.

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
Greater thangreaterThan(V)greater than the boundnumeric.greaterThanmin
Greater than or equalgreaterThanOrEqual(V)at least the boundnumeric.greaterThanOrEqualmin
Less thanlessThan(V)less than the boundnumeric.lessThanmax
Less than or equallessThanOrEqual(V)at most the boundnumeric.lessThanOrEqualmax
Positivepositive()greater than zeronumeric.positive-
Positive or zeropositiveOrZero()zero or greaternumeric.positiveOrZero-
Negativenegative()less than zeronumeric.negative-
Negative or zeronegativeOrZero()zero or lessnumeric.negativeOrZero-
MultiplemultipleOf(V)a multiple of the divisornumeric.multipleOfdivisor

multipleOf is available for Byte, Short, Integer, Long, BigInteger and BigDecimal; Character, Double and Float do not have it.

var quantityValidator = Yavi._integer("quantity", c -> c.multipleOf(12));
quantityValidator.validate(24);  // Valid
quantityValidator.validate(30);  // Invalid ("quantity" must be a multiple of 12)

BigInteger and BigDecimal

BigInteger and BigDecimal have the constraints of the integral types, including multipleOf. BigDecimal additionally has the constraints on the number of digits.

ConstraintMethodAccepted valuesMessage keyparams
Fraction digitsfractionDigits(int)at most the given number of digits after the decimal point; trailing zeros are not countednumeric.fractionDigitsmax
Integer digitsintegerDigits(int)at most the given number of digits before the decimal point; the zero of 0.5 is not countednumeric.integerDigitsmax

The comparisons use BigDecimal#compareTo and ignore the scale, so 1.0 and 1.00 are the same value and both have no fraction digit. The scale is not changed by the constraint; use preprocess or map when the produced value must have a fixed scale.

var priceValidator = Yavi._bigDecimal("price", c -> c.fractionDigits(2).integerDigits(6));
priceValidator.validate(new BigDecimal("1.50"));  // Valid (1.5 has one fraction digit)
priceValidator.validate(new BigDecimal("1.505")); // Invalid (numeric.fractionDigits)

Double and Float

_double and _float have notNull, isNull, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, positive, positiveOrZero, negative and negativeOrZero, with the same message keys as the integral types. They do not have multipleOf, because the remainder of a binary fraction is not exact. NaN satisfies none of the bounds and is rejected by every comparison.

Temporal

The temporal constraints are available for the following types, with the classic builder shortcuts. The schema style uses the same names as property methods, for example Yavi.schema()._localDate("date", c -> c.past()).

TypeConstraint classClassic shortcut
LocalDateLocalDateConstraint_localDate
LocalTimeLocalTimeConstraint_localTime
LocalDateTimeLocalDateTimeConstraint_localDateTime
OffsetDateTimeOffsetDateTimeConstraint_offsetDateTime
InstantInstantConstraint_instant
YearYearConstraint_year
YearMonthYearMonthConstraint_yearMonth
ZonedDateTimeZonedDateTimeConstraint_zonedDateTime
ConstraintMethodAccepted valuesMessage keyparams
Pastpast(), past(Clock)before the current timetemporal.past-
Past or presentpastOrPresent(), pastOrPresent(Clock)at or before the current timetemporal.pastOrPresent-
Futurefuture(), future(Clock)after the current timetemporal.future-
Future or presentfutureOrPresent(), futureOrPresent(Clock)at or after the current timetemporal.futureOrPresent-
Beforebefore(Supplier<T>)before the supplied boundarytemporal.beforeother
Before or equalbeforeOrEqual(Supplier<T>)at or before the supplied boundarytemporal.beforeOrEqualother
Afterafter(Supplier<T>)after the supplied boundarytemporal.afterother
After or equalafterOrEqual(Supplier<T>)at or after the supplied boundarytemporal.afterOrEqualother
Betweenbetween(Supplier<T>, Supplier<T>)strictly between the supplied boundstemporal.betweenrangeFrom, rangeTo
FieldfieldPredicate(TemporalField, LongPredicate)a value of the field accepted by the predicatetemporal.fieldfield

before, beforeOrEqual, after, afterOrEqual and between have an overload with a boolean memoize argument. It is true by default, so the supplier is called at most once and the same value is used for the comparison and the message. between throws IllegalArgumentException when rangeFrom is after rangeTo. The Clock overloads exist for deterministic tests and for a time source other than the system default zone.

A null value is valid and skips every temporal check.

Boolean

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
TrueisTrue()trueboolean.isTrue-
FalseisFalse()falseboolean.isFalse-

Collection and array

Use _collection for a Collection and _objectArray, _booleanArray, _byteArray, _charArray, _shortArray, _intArray, _longArray, _floatArray or _doubleArray for an array. The element or value validation of a list, a map and an array, including _list, _map and forEach, is described in Objects and Collections.

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
Not emptynotEmpty()a non-empty collection or arraycontainer.notEmpty-
Fixed sizefixedSize(int)the given number of elementscontainer.fixedSizesize, actualSize
Size greater thangreaterThan(int)more than the given numbercontainer.greaterThanmin, actualSize
Size greater than or equalgreaterThanOrEqual(int)at least the given numbercontainer.greaterThanOrEqualmin, actualSize
Size less thanlessThan(int)fewer than the given numbercontainer.lessThanmax, actualSize
Size less than or equallessThanOrEqual(int)at most the given numbercontainer.lessThanOrEqualmax, actualSize
Containscontains(E)a collection or array containing the elementcollection.contains, array.containselement
Uniqueunique()elements without duplicatescollection.uniqueduplicates
Unique by keyunique(Function<? super E, ?>)elements whose keys are uniquecollection.uniqueByduplicates
Contains allcontainsAll(Collection<? extends E>)all of the given elementscollection.containsAllvalues, missing

unique(key) reports the duplicated keys. A Set and a non-Set collection have the same semantics for containsAll. A null array is valid and the checks are skipped, except notEmpty().

var productsValidator = Yavi.schema()._list("products", productValidator, c -> c.unique(Product::id));
// "products" must be unique. [APPLE] is/are duplicated.

Map

Use _map for a Map.

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
Not emptynotEmpty()a non-empty mapcontainer.notEmpty-
Fixed sizefixedSize(int)the given number of entriescontainer.fixedSizesize, actualSize
Size greater thangreaterThan(int)more than the given numbercontainer.greaterThanmin, actualSize
Size greater than or equalgreaterThanOrEqual(int)at least the given numbercontainer.greaterThanOrEqualmin, actualSize
Size less thanlessThan(int)fewer than the given numbercontainer.lessThanmax, actualSize
Size less than or equallessThanOrEqual(int)at most the given numbercontainer.lessThanOrEqualmax, actualSize
Contains keycontainsKey(K)a map containing the keymap.containsKeykey
Contains valuecontainsValue(V)a map containing the valuemap.containsValuevalue

Object

Use _object for any other object. In the classic style, constraintOnTarget applies the constraints to the validated object itself.

ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
Equal toequalTo(Object)a value equal to the given valueobject.equalTovalue
One ofoneOf(Collection)one of the given valuesobject.oneOfvalues
Not one ofnotOneOf(Collection)none of the given valuesobject.notOneOfvalues
Password policypassword(policy -> ...)a value that meets the policies; a policy can inspect the whole objectpassword.required, password.optionalpolicy / min, policies

Enum

Use _enum for an enum. The schema style and the classic style both take the enum type.

var statusValidator = Yavi._enum("status", Status.class, c -> c.oneOf(Status.ACTIVE));
statusValidator.validate(Status.ACTIVE);   // Valid
statusValidator.validate(Status.INACTIVE); // Invalid ("status" must be one of the following values: [ACTIVE])
ConstraintMethodAccepted valuesMessage keyparams
Not nullnotNull()any non-null valueobject.notNull-
NullisNull()only nullobject.isNull-
One ofoneOf(E...)one of the given constants; the list must not be emptyobject.oneOfvalues

A null enum value is valid in the classic style unless notNull() is added. EnumValidatorBuilder and EnumValidator validate a single enum value.