Validations.pattern不适用于Regex [英] Validations.pattern doesn't work with 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屋!