【问题标题】:Angular: Validator Alphanumeric or Whitespace in FormbuilderAngular:Formbuilder中的验证器字母数字或空格
【发布时间】:2021-03-05 09:22:46
【问题描述】:

我想编写一个 Angular FormBuilder 验证器,它只允许字母数字字符、空字符串或空格。 (无符号),

以下不起作用,三种解决方案都没有, 我怎样才能让它在 Angular 中工作?

https://stackoverflow.com/a/36717690/15288973

this.formBuilder.group({
   productName: [null, [Validators.pattern(/^$|^[a-zA-Z0-9]+$/)]] 

这些应用在 Angular Material 文本框中,接收空字符串和空格的红色错误验证器。但是它至少适用于字母数字(无符号)。

【问题讨论】:

标签: angular regex typescript angular-reactive-forms angular11


【解决方案1】:

使用

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 材料在表单构建器中进行测试,接收到空字符串和空格的红色错误验证器。但是它至少适用于字母数字(无符号)。
  • @joecarl817 请访问演示链接,空格已匹配。检查该值是否不是required
  • 它有效!谢谢我删除了必填字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2023-03-29
  • 1970-01-01
  • 2013-11-06
  • 2022-08-03
  • 2013-11-04
  • 2019-06-07
相关资源
最近更新 更多