我是否正确使用PHP.js strpbrk函数?

时间:2009-07-02 20:30:44

标签: php javascript

我有以下JS功能:

function validatePass()
{
    var oldPass = document.getElementById("oldpass").value;
    var newPass1 = document.getElementById("newpass1").value;
    var newPass2 = document.getElementById("newpass2").value;
    if(strpbrk(newPass1,"abcdefghijklmnopqrstuvwxyz") != false)
    {
        document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
    }
    if(strpbrk(newPass1,"ABCDEFGHIJKLMNOPQRSTUVWXYZ") != false)
    {
        document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
    }
    if(strpbrk(newPass1,"1234567890") != false)
    {
        document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
        document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"red\">Not Met</span>";
    }
}

该代码调用PHP.js函数strpbrk来确定newPass1是否包含可接受的数据。在PHP中,strpbrk搜索haystack是否包含char_list中的任何字符。但是,在这个JS实现中,它会搜索所有字符。我怎样才能让它按照我想要的方式行事?

TIA。

1 个答案:

答案 0 :(得分:1)

我建议使用正则表达式而不是strpbrk。

function validatePass()
{
    var oldPass = document.getElementById("oldpass").value;
    var newPass1 = document.getElementById("newpass1").value;
    var newPass2 = document.getElementById("newpass2").value;
    if(/[a-z]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneLowercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
    }
    if(/[A-Z]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneUppercaseLetter").innerHTML = "<span id=\"red\">Not Met</span>";
    }
    if(/[0-9]/.test(newpass1))
    {
            document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"green\">Met</span>";
    }
    else
    {
            document.getElementById("ContainsAtLeastOneNumber").innerHTML = "<span id=\"red\">Not Met</span>";
    }
}