0
BGroup = new FormGroup({
  test: new FormControl(null, [Validators.required, Validators.pattern("[0-9]*$")])
});

Hi, I work with Angular 9 How can I set a pattern that takes only decimal numbers? Like the numbers below.

11 OR 11.30 OR 9 OR 9.40 OR 11.05 OR 16 OR 11.80 ......

max number =20

min number=0

2 Answers 2

1

Try:

BGroup = new FormGroup({    
    test: new FormControl(null, [Validators.required,
                Validators.pattern('^\\d*\\.?\\d*$'), 
        Validators.min(0),
        Validators.max(20)])
});
Sign up to request clarification or add additional context in comments.

3 Comments

Can you give an example? For which decimal number it can not match?
@Ali Please check regex101.com/r/HHYYUo/1, it matches perfectly.
@huanfeng, @Ali, The RegExp is correct, However edit the answer to below Validators.pattern('^\\d*\\.?\\d*$'), You need to escape the `\` character
1

Below works

constructor (private fb: FormBuilder) { }
pattern = '[0-9]+(\\.)?[0-9]*'
  BGroup = this.fb.group({    
    test: [null, [
      Validators.required, 
      Validators.pattern(this.pattern),
      Validators.min(0),
      Validators.max(20)
      ]
    ],
  });

I have created a Stackblitz Demo

2 Comments

I want to use a dot between decimals, for example (1.25) but the user can enter (1a25 or 1b25, etc.). And I do not want that to be the case.
Just added `\\` to escape the dot, Try now

Your Answer

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