RegexValidator function

TextValidator RegexValidator({
  1. required RegExp regex,
  2. MatchType matchType = MatchType.Entire,
  3. bool trim = false,
  4. bool allowEmpty = true,
  5. String message = "格式不符",
})

Implementation

TextValidator RegexValidator({required RegExp regex, MatchType matchType = MatchType.Entire, bool trim = false, bool allowEmpty = true, String message = "格式不符"}) {
  String? validator(String? text) {
    if (text == null || text.isEmpty) return allowEmpty ? null : message;
    String s = trim ? text.trim() : text;
    if (s.isEmpty) return allowEmpty ? null : message;
    RegExpMatch? m = regex.firstMatch(s);
    switch (matchType) {
      case MatchType.None:
        return m == null ? null : message;
      case MatchType.Start:
        return m?.start == 0 ? null : message;
      case MatchType.End:
        return m?.end == s.length ? null : message;
      case MatchType.Contains:
        return m != null ? null : message;
      case MatchType.Entire:
        return m?.start == 0 && m?.end == s.length ? null : message;
    }
  }

  return validator;
}