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
Asked
Active
Viewed 2,107 times
0

Flash
- 924
- 3
- 22
- 44
2 Answers
2
I think if you want to pass an expression, you should wrap pattern in square brackets. But more importantly, you cannot use the attribute pattern
in the tag textarea
, because pattern
is not an allowed attribute for textarea
.
As described in MDN Web Docs,
You can't provide specific regexs to validate the value against using the pattern attribute, like you can with the input element
So in your case I would either use an input
or consider using a CustomValidator
. If you use an input, make sure to wrap the expression in brackets:
<input type="text" [pattern]="condition ? pattern : noPattern">
Here's a tiny stackblitz with a working example of an input field.

RTYX
- 1,244
- 1
- 14
- 32
-
Thanks running some test now. I didn't realize pattern is not allowed in the text area – Flash Oct 16 '19 at 14:45
-
@Flash Happy to help. I added a stackblitz in case you find it useful. – RTYX Oct 16 '19 at 14:50
1
u want to pass any expression ? try this: <-input type="text" [pattern]="condition ? pattern : noPattern" >

Annas
- 35
- 4