用于测试8到15个字符之间的字符的JavaScript

时间:2014-09-23 21:41:35

标签: javascript

我必须测试一个javascript条件来测试表单上的字符输入,该表单应该接受8到15之间的字符,即不少于8且不超过15.一旦我检查了条件我发送消息给用户。以下是我正在使用但它似乎没有生成弹出窗口。

            if (PsWd.value.length > 0)
               //has to be more than 0
                if (PsWd.value.length > 15) 
               {
                //test the condition of more than 15 
                msg="The password needs to be less than 15";
               }
                // test for less than 8
               else if(PsWd.value.length < 8)                   
                {
                msg="The password needs to be have at least 8 characters: " 
                + PsWd.value.length +  PsWd.value.length;
                }                 
            }

2 个答案:

答案 0 :(得分:0)

试试这段代码

if (PsWd.value.length > 0)
{
    //has to be more than 0
    if (PsWd.value.length > 15) 
    {
    //test the condition of more than 15 
    msg="The password needs to be less than 15";
    alert(msg);
    }
    // test for less than 8
    else if(PsWd.value.length < 8)                   
    {
    msg="The password needs to be have at least 8 characters: " 
    + PsWd.value.length +  PsWd.value.length;
    alert(msg);
    }                 
}
else
{
    alert('insert password');
}

答案 1 :(得分:0)

如果问题代码较少,我会尝试一种方法:

我们假设我们有以下HTML表单:

<form id="myForm" onsubmit="return checkForm();" method="post">
    <input type="password" id="password">Password</input><br />
    <input type="submit">OK</input>
</form>

然后你的功能可能是这样的:

function checkForm() {
    var PsWd = document.getElementById('password');

    if (PsWd.value.length < 8 || PsWd.value.length > 15) {
        alert('The password length needs to be between 8 and 15 characters.');
        return false;
    } else {
        return true;
    }
}