.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.
Signature
Section titled “Signature”StringValidator<O> regex(RegExp pattern, {String? message, MessageBuilder? messageBuilder})Parameters
Section titled “Parameters”| 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.
Code generation
Section titled “Code generation”@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.
Example
Section titled “Example”final slug = l.string().regex(RegExp(r'^[a-z0-9-]+$'));@MatchRegex(r'^[a-z0-9-]+$') required String slug,// l.string().regex(RegExp(r'^[a-z0-9-]+$')).required()@MatchRegex(r'^[a-z]+$', caseSensitive: false) required String word,// l.string().regex(RegExp(r'^[a-z]+$', caseSensitive: false)).required()slug.validate(input)+1-1- valid:
'hello-world' - invalid:
'Hello World'
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;truetrue