Validations.pattern不适用于Regex [英] Validations.pattern doesn't work with Regex

查看:76
本文介绍了Validations.pattern不适用于Regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有反应形式,应使用模式.*[^\s].*验证其中一个控件.如果以模板驱动形式使用它,则效果很好.但在反应式的情况下-不会.我应该修改什么来解决它?

I have reactive form and one of the controls should be validated with the pattern .*[^\s].*. In case it is used in template-driven forms, it works well. But in a case of reactive - does not. What should I change to fix it?

this._form = this._formBuilder.group({
  description: ['', [Validators.required, Validators.pattern('.*[^\S].*')]]
}

推荐答案

看看重点是,正则表达式模式像正则表达式文字或字符串文字一样传递.当您将其作为正则表达式文字传递时,可以使用

The point is that the regex pattern is passed either like a regex literal, or as a string literal. When you pass it as a regex literal, you may use

/\S*\s.*/

将使用pattern.toString()将其转换"为字符串,并添加^$-"^\\S*\\s.*$".这正是您也可以在Validators.Pattern中传递的字符串模式.

It will be "converted" to a string with pattern.toString() and ^ and $ will be added - "^\\S*\\s.*$". This is exactly a string pattern you may pass in the Validators.Pattern, too.

请注意,^\S*\s.*$将匹配以0+个非空白字符开头,然后具有1个强制性空白,然后具有除换行符以外的任何0+个字符的字符串.它比/^.*\s.*$/快一点.请注意,\s = [^\S].

Note that ^\S*\s.*$ will match a string that starts with 0+ non-whitespace chars, then has 1 obligatory whitespace, and then has any 0+ chars other than line break chars. It is a bit faster than /^.*\s.*$/. Note that \s = [^\S].

这篇关于Validations.pattern不适用于Regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆