Search code examples
htmlangularvalidationng-patternng-required

Conditional pattern to be used along with required Angular7/8


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


Solution

  • 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.