Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: how to avoid special characters in validator

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?

like image 778
Little Monkey Avatar asked Oct 16 '18 12:10

Little Monkey


People also ask

How do you avoid special characters in flutter?

Here, we have string "str" with special characters, alphabets, numbers. We have used the replaceAll() method on string with RegEx expression to remove the special characters. It will give you the alphabets and numbers both and Special characters will be removed.


2 Answers

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'));
}
like image 177
Suragch Avatar answered Oct 09 '22 06:10

Suragch


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;
  }
}
like image 45
Kirollos Morkos Avatar answered Oct 09 '22 04:10

Kirollos Morkos