Home > Net >  How to put regex expression to validate number between 1.0 to 4.5 (range between decimal values)?
How to put regex expression to validate number between 1.0 to 4.5 (range between decimal values)?

Time:03-22

I need an expression to validate numbers between 1.0 to 4.5 but it's not working precisely for it.

Expression I'm using: /^[1-4]{0,1}(?:[.]\d{1,2})?$/

Requirement is to only accept value between 1.0 to 4.5

but

buildInserForm(): void {
    this.insertLeavesForm = this.fb.group({
     **your text**
      hours: [
        { value: 4.5, disabled: true },
        [
          Validators.required,
          Validators.pattern(**/^[1-4]{0,1}(?:[.]\d{1,2})?$/**),
        ],
      ],
    });
  }

Currently restricting the numbers from 1.0 to 4.0, But the issue comes in decimal points, it shows an error if entered any number between 6-9 in decimal places, like 1.7,2.8, 3.9.

acceptance criteria are 1.0 to 4.5.

CodePudding user response:

Regex are pretty bad to check number ranges. Should it consider non decimal numbers? What if there is more than one decimal point? What if you should ever want to increase/decrease range? Here's more on the topic: Regular expression Range with decimal 0.1 - 7.0

I would suggest simple min/max Validators. Plus this would also let you control if user value is below or above criteria, letting you to display custom error messages appropriately, for example. Whereas regex will simply evaluate to true/false.

[
 Validators.required,
 Validators.min(1),
 Validators.max(4.5)
]

CodePudding user response:

You may use the following regex pattern:

^(?:[1-3](?:\.\d{1,2})?|4(?:\.(?:[0-4][0-9]|50?)?))$

Demo

This regex pattern says to match:

^                            start of the input
(?:
    [1-3]                    match 1-3
    (?:\.\d{1,2})?           followed by optional decimal and 1 or 2 digits
    |                        OR
    4                        match 4
    (?:
        \.                   decimal point
        (?:[0-4][0-9]|50?)?  match 4.00 to 4.49 or 4.5 or 4.50
    )
)
$                            end of the input
  • Related