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?
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.
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'));
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With