-2

尝试验证用户名和密码,但即使用户名和密码正确,我也会收到错误消息。我得到一个TypeError,我做错了什么?我使用的是 String 方法吗?

function validateLogin() {
    let passwordInput = document.getElementById('password');
    let userName = document.getElementById('userName');

    event.preventDefault();

    // Set errors to an empty array
    let errors = [];

    // Conditions for password validation   

    if(passwordInput.length < 8) {
        errors.push('Your password must be at least 8 characters long')
    }
    if(passwordInput.search(/[a-z]/) < 0) {
        errors.push('Your password must cotain at least one lowercase letter')
    }
    if(passwordInput.search(/[A-Z]/) < 0) {
        errors.push('Your password must conatin at least one uppercase letter')
    }
    if(passwordInput.search(/[0-9]/) < 0) {
        errors.push('Password must contain at least one number!')
    }
    if(passwordInput.search(/[\!\@\#\$\%\^\&\*\(\)\_\+\.\,\;\:\-]/) < 0) {
        errors.push("Your password must contain at least one special character.")
    }

    // Login
    if (errors.length > 0) {
        document.getElementById("errors").innerHTML = errors.join("<br>")
        console.log('Error logging in')
        return false;
    } else if(errors.length < 0 && userName.value){
        console.log('Youre logged in!')
    }
};
4

1 回答 1

0

您正在TypeError继续,search因为search它是 的一个功能String,并且您在 . 的上下文中使用它element

您需要做的就是使用valueof passwordInput,它应该没问题。

而不是使用:

let passwordInput = document.getElementById('password');

这是类型element

你应该使用:

let passwordInput = document.getElementById('password').value;

类型的String

现在你应该可以使用了passwordInput.search,因为passwordInputis a String 并且searchis a string 函数。

于 2019-08-15T04:50:52.477 回答