24

I have this validation function:

class FormFieldValidator{
  static String validate(String value, String message){
    return (value.isEmpty || (value.contains(**SPECIAL CHARACTERS**))) ? message : null;
  }
}

I would like to indicate that doesn't have to contain special characters, but how can I say it?

Little Monkey
  • 5,395
  • 14
  • 45
  • 83

2 Answers2

65

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'));
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • How I can check if strings contain all spaces or special characters and invalidate them with regEx? – Ash Dec 02 '19 at 20:38
  • 1
    @Aks, Without having tried it myself, you might be able to create a set of invalid characters with something like `[^abc]`. Then if `hasMatch` returns true you would know that everything is an invalid character. Another option is to loop through each character. – Suragch Dec 04 '19 at 02:01
  • how about this character ' @Suragch – little_Friend Dec 11 '20 at 08:36
  • @little_Friend, You could use double quotes instead of single quotes if you're not also trying to match double quotes. Otherwise you could do something like [this](https://stackoverflow.com/a/58143313/3681880). – Suragch Dec 11 '20 at 09:19
  • Will it work for string containing emojis – Mirza Ahmed Baig Jun 12 '23 at 10:25
  • 1
    @MirzaAhmedBaig, If you are trying to exclude emojis, then yes, the answer here works. For example, `'abc123'` returns `false`. – Suragch Jun 13 '23 at 02:07
5

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;
  }
}
Kirollos Morkos
  • 2,503
  • 16
  • 22