Regex static method

String? Function(String? value)? Regex({
  1. required String pattern,
  2. String errorMessage = 'Invalid value',
  3. String? next(
    1. String value
    )?,
})

Returns a validator that checks if a string is matches given regex pattern.

Arguments :

  • pattern : The regex pattern to match.
  • errorMessage : The error message to return if the string does not match the pattern.
  • next : A validator to run after this validator.

Usage :

TextFormField(
validator: Validators.Regex(pattern: r'^[a-zA-Z]+$'),
),

Implementation

static String? Function(String? value)? Regex({
  required String pattern,
  String errorMessage = 'Invalid value',
  String? Function(String value)? next,
}) {
  return (value) {
    if (value == null || value.trim().isEmpty) {
      return null;
    }

    if (!RegExp(pattern).hasMatch(value)) {
      return errorMessage;
    }

    if (next != null) {
      return next(value);
    }

    return null;
  };
}