Flutter: how to avoid special characters in validator

放肆的年华 提交于 2020-03-22 08:59:08

问题


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?


回答1:


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'));
}



回答2:


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;
  }
}


来源:https://stackoverflow.com/questions/52835450/flutter-how-to-avoid-special-characters-in-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!