[SOLVED] How to put regex expression to validate number between 1.0 to 4.5 (range between decimal values)?

Issue

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.

Picture of showing where value is being entered wrong

This image shows that value is getting entered to multiple decimal places which is wrong,
Only single decimal place value is required.

Solution

This is a regex that I created.
pattern(/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/)

Explaination

/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/


/^            start of the input
[1-3]         First input to be taken between
{0,1}         This shows how many times it can be repeated
(             Parenthesis shows next entered digit is optional
?             Question mark is for using digit zero or once
:[.]          This is for what the next Character would be eg ".", "@"
[0-9]         input to be taken between.
{0,1}         This shows how many times it can be repeated.
)             Option part closes
?             Question mark is for using digit zero or once.
[4]           This shows what can be other input that can be taken
{0,1}         How many times it can be use , SO in this case 0 or 1 times


(?:[.]       There after again same option part  with decimal point

             decimal value of 4and its limitation for 0 to 5
[0-5]        This is to set limitation 0-5 as per our requirement
{0,1}        Its existence 0 or 1 times
)            Close of optional part.
?            Thereafter showing the existence of an optional part once or twice.
$/           Shows to match expression after it.

Answered By – Aman Kumar Singh

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *