简体   繁体   English

验证始终无法验证

[英]Validation Always Failing To Validate

Tried to add in some validation to a form, but it keeps acting as if the data that is being validated is invalid, even if its valid! 试图在表单中添加一些验证,但它仍然表现得好像正在验证的数据无效,即使它有效!

if (document.getElementById("mileageNumber").value  == /^[0-9]+$/)
{
    if (document.getElementById("vehicleNumber").value  == /^[0-9]+$/)
    {
        <Desired Action>
    }
    else
    {
        alert("Please Enter Numbers Only");
    }
}
else
{
    alert("Please Enter Numbers Only");
}

Can anybody see what i have done wrong? 谁能看到我做错了什么?

You need to use the RegExp.test method. 您需要使用RegExp.test方法。

/^[0-9]+$/.test(document.getElementById("mileageNumber").value);

You can also simplify your regular expression like so: /^\\d+$/ 你也可以这样简化你的正则表达式: /^\\d+$/

You'll need to test the regex and not evaluate it as a value. 您需要测试正则表达式而不是将其评估为值。

if(/^[0-9]+$/.test(document.getElementById("vehicleNumber").value)){

    //Validation passed

}

You are comparing a string with a regex object. 您正在将字符串与正则表达式对象进行比较。 A regex object describes a structure of a regex object. 正则表达式对象描述了正则表达式对象的结构。 A string is just a bunch of characters. 字符串只是一堆字符。 They are simply not the same thing... ever. 它们根本不是一回事......永远。 Just like the pseudo-code apples == carrots will never return true, string == regex will never return either. 就像伪代码apples == carrots永远不会返回true一样, string == regex也永远不会返回。 It requires a function to test if a string has the structure that the regex object describes. 它需要一个函数来测试字符串是否具有正则表达式对象描述的结构。

You can properly test a string against a regex using string.match( .. ) . 您可以使用string.match( .. )针对正则表达式正确测试字符串。

document.getElementById("vehicleNumber").value.match( /^[0-9]+$/ );

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

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