enzio902
enzio902

Reputation: 467

PatternValidator directive doesn't validate when the correct regex string value is passed to it

I have an input field whose input should be a positive number.

    <input  type="number" [(ngModel)]='assetValue'
     type="number" pattern="positiveNumberRegex">

positiveNumber() returns a RegExp. I store it's string value in a variable. This is done in the OnInit Life cycle hook.

this.positiveNumberRegex = this.regexPatternService.positiveNumber().source;
console.log(this.positiveNumberRegex); // ^[1-9][0-9]*[.]?[0-9]*$

But the validation fails when I enter a positive number.

If I hardcode the regex to the pattern directive, it works fine.

    <input  type="number" [(ngModel)]='assetValue'
     type="number" pattern="^[1-9][0-9]*[.]?[0-9]*$">

What is the reason for this?

Upvotes: 0

Views: 304

Answers (2)

Qellson
Qellson

Reputation: 552

[pattern] brackets tell angular to read whats in the expression positiveNumberRegex, without the brackets it treats it as a regular string

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

use the [] around pattern to support the binding.

 [pattern]="positiveNumberRegex">

Upvotes: 2

Related Questions