简体   繁体   English

JavaScript RegEX测试不起作用

[英]JavaScript RegEX Test not working

I want to check if input text (amount) is between 1-100 or not but regex test not working. 我想检查输入的文本(数量)是否在1-100之间,但是正则表达式测试不起作用。

here is my JS code 这是我的JS代码

<script type="text/javascript" >    

    console.log(document.getElementById("amount").value); // 222

    var regex = /^(100)|[1-9]\d?$/;
    if(regex.test(document.getElementById("amount").value))
    {
        alert('validated')
    }
    else
        alert('error')

</script>
  1. Wrap the code in DOMContentLoaded event callback 将代码包装在DOMContentLoaded事件回调中
  2. Don't use RegEx. 不要使用RegEx。 Use comparison operators 使用比较运算符

Code: 码:

document.addEventListener('DOMContentLoaded', function () {
    // Get the value & convert it into Number
    var value = parseInt(document.getElementById('amount').value, 10);

    // Value between 0 & 100
    if (value > 0 && value <= 100) {
        alert('Valid');
    } else {
        alert('Error');
    }
});

It would be enough to use parseInt() function or Number constructor to perform such a simple validation: 使用parseInt()函数或Number构造函数执行这样的简单验证就足够了:

<script type="text/javascript" >
    var amount = Number(document.getElementById("amount").value); // 222
    alert ((amount > 0 && amount <= 100)? 'Valid' : 'Invalid');
</script> 

If you really want to use regex, this should work: 如果您确实要使用正则表达式,则应该可以使用:

/^100$|^[1-9]\d?$/

It doesn't allow eg 09 , but maybe that's OK. 例如,它不允许使用09 ,但是也许可以。

    <html>
    <head>

    <script>

    function validateValue()
    {
    var amount = document.getElementById('testId').value;
    if((isNaN(amount ))){
    document.getElementById("errorId").style.display= "";
    }
    else
    {
    if(amount>100){
    document.getElementById("errorId").style.display= "";
    }
    else
    {
    document.getElementById("errorId").style.display= "none";
    }
    }
    }

    </script>

    </head>
    <body>

    Enter 1 to 100:<input type="text" onkeyup="validateValue()"         id="testId"/>
    <span id="errorId" style="color:red;display:none"> Not a valid amount</span>
    </body>
    </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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