验证用户名onchange

时间:2015-02-16 20:14:40

标签: javascript onchange

我正在尝试在jsp页面上验证我的用户名。基本上我想看看是否有匹配的域我想重定向到其他URL。下面是我的功能。

function validateName()
{
    var UserName=document.getElementById('Username').value;

    if (UserName == "@test.com")
    {
        window.location="http://test.test.com";
    }
    else if (UserName == "@test1.com")
    {
        window.location="https://test.test1.com";
    }
    return true
}

我的表单有onchange事件。

<p>
Enter the UserName: <input id="Username" name="Username" onchange="validateName()"><br>
</p>

我该如何验证这一点?我不知道上面的工作。每当我试图放一些&#34; test.com&#34;或&#34; test1.com&#34;我没有看到表格中发生的任何事情。

如果你能对此有所了解,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

使用onkeyup="validateName()"代替onchange="validateName()"

答案 1 :(得分:0)

永远不要使用var name,以前用作object id的相同字符串......

object ID&amp;你要使用的var name必须是不同的(不区分大小写)

// This:
var UserName = document.getElementById('Username').value;
     \            \
      \_ Var Name  \
                    \_ Object Property

// is the same as:
var UserName = Username.value;
     \            \
      \_ Var Name  \
                    \_ Object Property

有了这个,(记住,不区分大小写)你的var name与你的object ID有冲突,所以在你的函数中,你实际上是在比较:

if ( username == username.value ) {...}
      \            \
       \_ Object    \
                     \_ Object Property
// will never be true

所以,简而言之...... 使用其他内容更改函数中的var名称。

function validateName()
{
    var UserNameToCheck = document.getElementById('Username').value;

    if (UserNameToCheck == "@test.com")
    {
        alert("http://test.test.com");
        //window.location="http://test.test.com";
    }
    else if (UserNameToCheck == "@test1.com")
    {
        alert("http://test.test1.com");
        //window.location="https://test.test1.com";
    }
    return true
}
<p>
Enter the UserName: <input id="Username" name="Username" onchange="validateName()"><br>
</p>

...或根本不使用它并直接检查......

function validateName()
{
    if ( Username.value == "@test.com" ) {...}
}
相关问题