kaitlynjanine
kaitlynjanine

Reputation: 63

How Can I Use a Regular Expression to Test for a Specific Decimal?

I have a field where the user needs to input the width of their window. It needs to be between 16.75 and 48 and only in .25 increments (so it has to end in .00, .25, .50, .75). I have tried the following to test my regular expressions on the number 31.25 but the all return false. I've trolled the internet but can't find much help for a regex novice like me. Can someone please help me with the regex for this?

Here is the field:

<input type="text" id="windowWidth" onchange="basePrice()">

Here is the JS:

function basePrice()
{
    var windowWidth = document.getElementById("windowWidth").value;
    var windowHeight = document.getElementById("windowHeight").value;

    if (windowWidth != "" && windowWidth > 16.75 && windowWidth < 48)
    {
         alert(/^\d{2}\.[00]$/.test(windowWidth));
         alert(/^\d{2}\.[25]$/.test(windowWidth));
         alert(/^\d{2}\.[50]$/.test(windowWidth));
         alert(/^\d{2}\.[75]$/.test(windowWidth));
    }
    else
    {
         alert("error");
         exit;
    }
}

Upvotes: 1

Views: 160

Answers (5)

plalx
plalx

Reputation: 43718

You do not need a regular expression for this. You can simply use math expressions.

var n = 35.23;

n >= 16.75 && n <= 48 && !(n % .25); //false

n = 35.25;

n >= 16.75 && n <= 48 && !(n % .25); //true

Upvotes: 2

Sharlike
Sharlike

Reputation: 1789

If you can use html 5 input attributes, then you could try this (without regular expressions):

<input type="number" id="windowWidth" onchange="basePrice()" min="16.75" max="48" step="0.25">

This would enforce the minimum and maximum and change by 0.25 when clicking the up or down arrows.

Upvotes: 1

ced-b
ced-b

Reputation: 4065

Here is a non-regex way of doing it, which is possibly more efficient and less messy:

var has25decimal = (windowWidth * 100) % 25 == 0

The % (modulo) gives you the remainder after the number has been divided by 25. When that is 0 the number can be divided by 25.

Upvotes: 1

Paul Gleeson
Paul Gleeson

Reputation: 438

You could probably combine them to test if they fell within your range and then used the following regex :

/^\d{2}\.(00|25|50|75)$/

Upvotes: 2

anubhava
anubhava

Reputation: 785058

Remove [ and ], that is used for character class in regex:

alert(/^\d{2}\.(?:00|25|50|75)$/.test(windowWidth));

For ex: [00] means match literal 0 or 0

OR [25] means match 2 or 5

Upvotes: 3

Related Questions