0

In my template driven form the textarea is required based on a condtion. I would also like the pattern to be conditional. I tried this syntax based on a question from angular 1.x but it doesn't seem to work. - pattern=" condition ? '.*[^ ].*' : ''" I also tried - pattern="condition ? (\s*[^\s]+\s*)+ : .*". is this possible with the later versions of Angular? Here is my stack blitz: https://stackblitz.com/edit/conditionalpattern

4

2 回答 2

2

我认为如果你想传递一个表达式,你应该用方括号将模式括起来。但更重要的是,您不能pattern在标签中textareapattern使用该属性,因为textarea.

MDN Web Docs中所述,

您不能提供特定的正则表达式来验证使用模式属性的值,就像您可以使用输入元素一样

因此,在您的情况下,我会使用input或考虑使用CustomValidator. 如果使用输入,请确保将表达式括在括号中:

<input type="text" [pattern]="condition ? pattern : noPattern">

这是一个带有输入字段工作示例的小型堆栈闪电战。

于 2019-10-16T14:23:18.100 回答
1

你想传递任何表达式吗?试试这个:<-input type="text" [pattern]="condition ? pattern : noPattern" >

于 2019-10-16T15:03:18.100 回答