gpt4 book ai didi

javascript - 在 JavaScript 函数中返回 bool 值

转载 作者:行者123 更新时间:2023-12-03 08:22:09 25 4
gpt4 key购买 nike

我正在进行客户端表单验证以检查密码是否匹配。但是验证函数总是返回 undefined .

function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");

if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}

请注意 validatePassword从 Form 对象的成员函数中调用。
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}

Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}

//result is always undefined
if(result)
{
//do other stuff
}
}

最佳答案

你可以简化很多:

  • 检查一个是否不为空
  • 检查它们是否相等

  • 这将导致这个,它总是返回一个 bool 值。你的函数也应该总是返回一个 bool 值,但是如果你简化你的代码,你会发现它做得更好:
    function validatePassword()
    {
    var password = document.getElementById("password");
    var confirm_password = document.getElementById("password_confirm");

    return password.value !== "" && password.value === confirm_password.value;
    // not empty and equal
    }

    关于javascript - 在 JavaScript 函数中返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7770187/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com