简体   繁体   English

为什么我的代码无法识别密码包含字符?

[英]Why is my code not able to recognize that a password contains characters?

I am making a login form. 我正在填写登录表格。 Before it submits, I check if all the fields are filled in. I also check if the password is longer than 7 characters and contains at least one number, at least one character, and no spaces. 在提交之前,我检查是否所有字段都已填写。我还检查密码是否超过7个字符,并且包含至少一个数字,至少一个字符且没有空格。 My current code keeps on telling me that I am missing a character no matter what I enter. 我当前的代码不断告诉我,无论输入什么内容,我都会缺少一个字符。 This is the code: 这是代码:

if($("#password").val()==""){

        error += "The password is required.<br>";   

    }
    else if($("#password").val().length<8){

        error += "Your password needs at least 8 characters.<br>";   

    }
    else if($("#password").val().length >= 8){

        var pass = $("#password").val().split("");

        var hasNum = false;

        var hasChar = false;

        var hasSpace = false;

        for(var i = 0; i < pass.length; i++){

            if(pass[i] == " "){

                hasSpace = true;

            }
            else if(Number(pass[i]) == NaN){

                hasChar = true;

            }
            else if(Number(pass[i]) != NaN){

                hasNum = true;

            }


        }

        if(!hasChar){

            error += "Your password must contain at least one character.<br>";

        }
        if(!hasNum){

            error += "Your password must contain at least one number.<br>";

        }
        if(hasSpace){

             error += "Spaces are not allowed in a password.<br>";   

        }

    }

I first check for a space. 我首先检查一个空间。 Then I check if a character can be converted to a number. 然后,我检查字符是否可以转换为数字。 If not, then it must be a string. 如果不是,则它必须是字符串。 If it can be converted, it must be a number. 如果可以转换,则必须为数字。 Whatever I type in, it always says "Your password must contain at least one character". 无论我输入什么,它总是说“您的密码必须至少包含一个字符”。 How can I fix this? 我怎样才能解决这个问题? I will give you more code if it is necessary. 如果有必要,我会给您更多代码。

The problem is that NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value: 问题在于NaN会将不相等的值(通过==,!=,===和!==)与任何其他值(包括与另一个NaN值)进行比较:

NaN === NaN;// false
Number('S') == NaN; //false
Number(10) == NaN; //false

try to use isNaN() instead. 尝试改用isNaN()

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

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