Angular:Formbuilder 中的验证器字母数字或空格
Angular: Validator Alphanumeric or Whitespace in Formbuilder
我想编写一个 Angular FormBuilder 验证程序,它只允许字母数字字符、空字符串或空格。 (没有符号),
以下是行不通的,none三种解决方案,
我怎样才能让它在 Angular 中工作?
this.formBuilder.group({
productName: [null, [Validators.pattern(/^$|^[a-zA-Z0-9]+$/)]]
这些正在 Angular Material 文本框中应用,接收空字符串和空格的红色错误验证器。但是它至少适用于字母数字(无符号)。
使用
Validators.pattern(/^(?:[a-zA-Z0-9\s]+)?$/)
参见proof。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[a-zA-Z0-9\s]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', whitespace (\n, \r, \t,
\f, and " ") (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
我想编写一个 Angular FormBuilder 验证程序,它只允许字母数字字符、空字符串或空格。 (没有符号),
以下是行不通的,none三种解决方案, 我怎样才能让它在 Angular 中工作?
this.formBuilder.group({
productName: [null, [Validators.pattern(/^$|^[a-zA-Z0-9]+$/)]]
这些正在 Angular Material 文本框中应用,接收空字符串和空格的红色错误验证器。但是它至少适用于字母数字(无符号)。
使用
Validators.pattern(/^(?:[a-zA-Z0-9\s]+)?$/)
参见proof。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[a-zA-Z0-9\s]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', whitespace (\n, \r, \t,
\f, and " ") (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string