What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately.

The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/

The requirement is to only allow values between 1.0 to 4.5

However,

buildInsertForm(): 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 there is an issue with decimal points as it shows an error for numbers like 1.7, 2.8, and 3.9.

The acceptance criteria are values between 1.0 and 4.5.

https://i.stack.imgur.com/VZ6Yh.png

This image demonstrates that the input allows multiple decimal places which is incorrect,
Only a single decimal place value should be accepted.

Answer №1

Checking number ranges using regular expressions can be challenging, especially when dealing with non-decimal numbers or multiple decimal points. Additionally, modifying the range can be cumbersome. For a simpler solution, consider using min/max Validators instead. These validators not only allow you to specify the minimum and maximum values, but also enable you to provide custom error messages based on user input. This approach offers more control compared to regex which only provides true/false evaluation.

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

Answer №2

You can utilize the below regular expression pattern:

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

Check out the Demo here

This regex pattern is designed to match:

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

Answer №3

I have developed a regex pattern that I would like to share. pattern(/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/)

Explanation

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


/^            Indicates the start of the input
[1-3]         Specifies the range for the first digit
{0,1}         Denotes how many times it can be repeated
(             Parentheses indicate the next entered digit is optional
?             Represents zero or one occurrence of the previous element
:[.]          Indicates what the following character would be, e.g., "."
[0-9]         Specifies numbers between 0 and 9
{0,1}         Shows how many times it can be repeated.
)             Closes the optional part
?             Denotes the presence of the digit being optional
[4]           Specifies another possible input
{0,1}         Specifies how many times it can be used, in this case, 0 or 1 times.


(?:[.]       Same optional part with decimal point

             Specifies a decimal value of 4 within the limit of 0 to 5
[0-5]        Sets the limitation from 0 to 5 as required
{0,1}        Specifies its existence either 0 or 1 time
)            Closes the optional part
?            Indicates the optional part occurs once or twice.
$/           Matches the expression before it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to execute a simple hello_world.ts script following a recent TypeScript installation on WSL

I've recently ventured into the realm of Typescript and decided to kick things off by following the official 5-minute tutorial available at: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html npm install -g typescript However, ...

The variable 'key' is declared in the Google Chrome extension V3 local storage, but it appears that its assigned value is never actually accessed

In my TypeScript code, I have defined a function like so: setLocalStorage: async (key: string, value: string): Promise<string> => { return new Promise((resolve, reject) => { chrome.storage.local.set({ key: value }, funct ...

Issue encountered while configuring server using express.js

Here is the server.js file I am working on, but I encounter a specific error when trying to set up the server with Express.js var express = require('express'); var app = express(); var PORT = process.env.PORT || 3000; app.all('/*', ...

The Angular 4 application is unable to proceed with the request due to lack of authorization

Hello, I am encountering an issue specifically when making a post request rather than a get request. The authorization for this particular request has been denied. Interestingly, this function works perfectly fine with my WPF APP and even on Postman. B ...

Select2 version 4.0.3 encountering issues when trying to automatically populate additional select2 fields with data fetched through ajax

I'm encountering an issue with Select2. Essentially, I need to populate other form fields with data retrieved from Select2's Ajax search. Even after following an example found here: Select2 4.0 - Push new entry after creation I'm still un ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

JQuery is unable to detect the response from PHP's echo statement

Receiving an 'ok' message from a PHP script through a JQuery ajax call has become quite the challenge for me. I am able to successfully display the correct message in the console when I log it, but for some reason, the corresponding jQuery funct ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

Angular 2 - update browsing history by replacing instead of adding to it

Is it possible to replace the history instead of pushing a new one in Angular 2's new router (rc.1)? For instance, suppose I am in a question list (/questions), then open a new modal in a new route (/questions/add). After adding a new question, I nav ...

Tips for extracting and structuring strings from unstructured CSV data using JavaScript?

From a public source, I've extracted a string of allergy data: Cedar 679 gr/m3 High, Grass 20 gr/m3 Medium, Trees 80 gr/m3 Medium, Molds Low. Although the number of items may vary, the standard format for trees and grasses is consistent, with allerge ...

Custom Sign-in features in NextJS now direct users to the default form for entering login

I have been working on a web app that requires authentication using NextJS default auth middleware. However, whenever I try to log in, the app redirects me to the default NextJS form component at the URL /api/auth/signin?error=CredentialsSignin. Even thou ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

Angular: The object you supplied is not compatible with a stream. Be sure to pass in an Observable, Promise, Array, or Iterable instead

I'm currently working on implementing the Material autocomplete component with filtering using my own array of values. However, I encountered the following error: core.js:1624 ERROR TypeError: You provided an invalid object where a stream was expecte ...

React hooks - Issue with updating state properties within sidebar display

When resizing the window, I have an event that will display either the desktop sidebar or the mobile sidebar. However, there are variables that are not immediately updated to show the sidebar correctly based on the window size. In a desktop window, this ca ...

What are the steps for transmitting an array of data to Parse Cloud Code?

Trying to send an array of contact emails as a parameter in Cloud Code function for Parse, here is how I am doing it: HashMap<String, ArrayList<String>> params = new HashMap<>(); ArrayList<String> array = new ArrayList<>(); a ...

VueJS - repeating input fields for file uploads

I need help removing duplicate items from an array in JavaScript, but when I try to delete one, it always deletes the last occurrence! let app = new Vue({ el: '#app', data: { items: [] }, methods: { addItem() { this.items ...

Modifying an HTML attribute dynamically in D3 by evaluating its existing value

I'm facing a seemingly simple task, but I can't quite crack it. My web page showcases multiple bar graphs, and I'm aiming to create a button that reveals or conceals certain bars. Specifically, when toggled, I want half of the bars to vanish ...

Guide to incorporating code coverage in React/NextJs using Typescript (create-next-app) and cypress

I initiated a fresh project using create-next-app with the default settings. npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365544535742531b58534e421b57464676070518021801">[email protected]</a> --- Would you l ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...