0

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?

2 Answers 2

2

use the [] around pattern to support the binding.

 [pattern]="positiveNumberRegex">
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you It worked! But why did it work with the hardcoded value earlier?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.