Reputation: 6157
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?
Upvotes: 28
Views: 41275
Reputation: 511626
Here is a somewhat more general answer.
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&%=]+$');
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.
validCharacters.hasMatch('abc123'); // true
validCharacters.hasMatch('abc 123'); // false (spaces not allowed)
void main() {
final validCharacters = RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$');
print(validCharacters.hasMatch('abc123'));
}
Upvotes: 72
Reputation: 2711
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;
}
}
Upvotes: 6