gpt4 book ai didi

javascript - 检查 Javascript 中的字段是否为空?

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

我正在尝试检查特定字段是否为空,以便我可以使用 Firebase 对用户进行身份验证。然而,JavaScript 似乎跳过了多段代码,并且不断地只在屏幕上显示相同的消息。这是我的代码...

let user = document.getElementsByName('username');
let em2 = document.getElementsByName('mail2');
let rem = document.getElementsByName('repeatMail');
let pass2 = document.getElementsByName('password2');
let rpass = document.getElementsByName('repeatPassword');

if ((user === '') && (em2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((rem === '') && (pass2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if (rpass === '') {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((em2 !== rem) && (pass2 !== rpass)) {
alert('Please make sure all repeat fields match their parents. Thank you');
} else {
checkUsername()
}

它会不断地跳到最后一个 else if 语句,无论什么都会给我设置错误,即使字段在 HTML 中确实匹配。我可能只是忽略了一些事情,但我已经为此苦苦挣扎了一段时间。有谁知道解决方案吗?顺便说一句,这段代码位于一个函数内部,但我给了它一个唯一的名称,它只是一个简单的...

function regSecurity() {

}

最佳答案

除了输入元素的 neede value 属性之外,您还需要检查是否为空,然后检查两个所需的输入是否相同。

function checkUsername() {
console.log('checkUsername');
return false;
}

function check() {
let user = document.getElementById('username').value,
em2 = document.getElementById('mail2').value,
rem = document.getElementById('repeatMail').value,
pass2 = document.getElementById('password2').value,
rpass = document.getElementById('repeatPassword').value;

if (!user || !em2 || !rem || !pass2 || !rpass) {
alert('Please make sure all fields are filled in correctly. Thank you');
return false;
}
if (em2 !== rem || pass2 !== rpass) {
alert('Please make sure all repeat fields match their parents. Thank you');
return false;
}
return checkUsername();
}
<form onsubmit="return check()">
<input type="text" id="username" placeholder="username">
<input type="text" id="mail2" placeholder="mail2">
<input type="text" id="repeatMail" placeholder="repeatMail">
<input type="text" id="password2" placeholder="password2">
<input type="text" id="repeatPassword" placeholder="repeatPassword">
<input type="submit">
</form>

关于javascript - 检查 Javascript 中的字段是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54862239/

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