简体   繁体   中英

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;
    }
}

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

您可能可以组合使用它们来测试它们是否落在您的范围内,然后使用以下正则表达式:

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM