3

I am not able to bind variable from component as a pattern with Angular 4. This code works:

<textarea #sss="ngModel"
    class="form-control"
    id="sss"
    maxlength="350"
    pattern="[a-zA-Z '-,;.]*"
    [(ngModel)]="formModel.sss" name="sss"></textarea>

But when I try to add something like:

export class SssComponent {
    public sssPattern: string = "[a-zA-Z '-,;.]*";

and add it like that:

<textarea #sss="ngModel"
    class="form-control"
    id="sss"
    maxlength="350"
    pattern="sssPattern"
    [(ngModel)]="formModel.sss" name="sss"></textarea>

it don't. Also tried variations like:

[pattern]="sssPattern"
[pattern]={{sssPattern}}
pattern={{sssPattern}}

with no success. Angular 4

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84

2 Answers2

3

You have to use attr.pattern, because pattern is an attribute with no reflection from a property:

<textarea [attr.pattern]="sssPattern"></textarea>

Interpolation and property binding can set only properties, not attributes.

You need attribute bindings to create and bind to such attributes.

Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr, followed by a dot (.) and the name of the attribute. You then set the attribute value, using an expression that resolves to a string.

read more

You cannot use pattern on a textarea. Angular does have its own PatternValidator, which means all that nonsense I said about attr does not hold up for this specific case, but I believe this does not work on a textarea, because textarea itself does not contain the pattern attribute in standard HTML5, as opposed to the input element.

In order to use a pattern on a textarea, you should create a CustomValidator

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • @TeodorKolev are you using single quotes here? `'[a-zA-Z '-,;.]*'`, because that would be a syntax error.. You have to escape the single quote inside the regex. Do you have any error coming up? – Poul Kruijt Nov 06 '17 at 18:24
  • I use doule quotes actually – IntoTheDeep Nov 06 '17 at 18:26
  • can you please help me to solve this https://stackoverflow.com/questions/52091334/password-validation-is-not-working-in-angular-5 @PierreDuc – Zhu Aug 30 '18 at 08:35
2

If you use Angular Forms, below code can be used for field and pattern validation

let emailFormat = "[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}";
let nameFormat = "[a-zA-Z\s]+$";

this.name = new FormControl("", Validators.compose([Validators.required, Validators.pattern(nameFormat)]));
this.email = new FormControl("", Validators.compose([Validators.required, Validators.pattern(emailFormat)]));
Prithivi Raj
  • 2,658
  • 1
  • 19
  • 34