Flutter: how to avoid special characters in validator

You can use a regular expression to check if the string is alphanumeric.

class FormFieldValidator {
  static String validate(String value, String message) {
    return RegExp(r"^[a-zA-Z0-9]+$").hasMatch(value) ? null : message;
  }
}

Here is a somewhat more general answer.

1. Define the valid characters

Add the characters you want within the [ ] square brackets. (You can add a range of characters by using a - dash.):

// alphanumeric
static final  validCharacters = RegExp(r'^[a-zA-Z0-9]+$');

The regex above matches upper and lowercase letters and numbers. If you need other characters you can add them. For example, the next regex also matches &, %, and =.

// alphanumeric and &%=
static final validCharacters = RegExp(r'^[a-zA-Z0-9&%=]+$');

Escaping characters

Certain characters have special meaning in a regex and need to be escaped with a \ backslash:

  • (, ), [, ], {, }, *, +, ?, ., ^, $, | and \.

So if your requirements were alphanumeric characters and _-=@,.;, then the regex would be:

// alphanumeric and _-=@,.;
static final validCharacters = RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$');

The - and the . were escaped.

2. Test a string

validCharacters.hasMatch('abc123');  // true
validCharacters.hasMatch('abc 123'); // false (spaces not allowed)

Try it yourself in DartPad

void main() {
  final validCharacters = RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$');
  print(validCharacters.hasMatch('abc123'));
}