Flutter:如何避免验证器中的特殊字符 [英] Flutter: how to avoid special characters in validator
问题描述
我具有此验证功能:
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 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&%=]+$');
转义字符
某些字符有特殊含义正则表达式中的意思,需要用 \
反斜杠转义:
-
(
,)
,[
,]
,{
,}
,*
,+
,?
,。
,^
,$
,|
和\
。
(
,)
,[
,]
,{
,}
,*
,+
,?
,.
,^
,$
,|
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_\-=@,\.;]+$');
-
和。
被逃脱了。
validCharacters.hasMatch('abc123'); // true
validCharacters.hasMatch('abc 123'); // false (spaces not allowed)
在 DartPad
Try it yourself in DartPad
void main() {
final validCharacters = RegExp(r'^[a-zA-Z0-9_\-=@,\.;]+$');
print(validCharacters.hasMatch('abc123'));
}
这篇关于Flutter:如何避免验证器中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!