Skip to content

.regex()

Passes when pattern.hasMatch(value) is true. The pattern is a RegExp, so its flags apply and an invalid pattern throws where the validator is built rather than where it runs. It is not anchored for you: RegExp(r'[0-9]') accepts 'abc1def'. Add ^ and $ when the whole string has to match.

StringValidator<O> regex(RegExp pattern, {String? message, MessageBuilder? messageBuilder})
Parameter Type Meaning
pattern RegExp The pattern. Use a raw string literal inside RegExp(...). params['pattern'] holds its source.
message String? Replaces the default error message.
messageBuilder MessageBuilder? Builds the message from the issue. message wins when both are given. See Message builders.

Code invalidPattern. Default message: value must match the pattern ^[a-z0-9-]+$, naming the pattern. value is replaced by the field name when there is one.

@MatchRegex(r'...'), with the optional flags caseSensitive, multiLine, unicode and dotAll. The generator builds the RegExp and passes flags that differ from the default. Put the annotation on the constructor parameter or the field.

final slug = l.string().regex(RegExp(r'^[a-z0-9-]+$'));
slug.validate(input)+1-1
  1. valid: 'hello-world'
  2. invalid: 'Hello World'value must match the pattern ^[a-z0-9-]+$

Flags and anchoring:

l.string().regex(RegExp(r'^[a-z]+$', caseSensitive: false)).validate('Hello').isValid;
l.string().regex(RegExp(r'[0-9]')).validate('abc1def').isValid;
true
true