gpt4 book ai didi

javascript - 如何使用javascript显示提交时的所有错误

转载 作者:行者123 更新时间:2023-12-01 02:36:19 28 4
gpt4 key购买 nike

我想知道当用户提交表单时如何立即显示所有已验证的错误。到这里为止,它工作正常,但它一一显示错误。

const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",

];
const reg = /^\d+$/;

form.addEventListener('submit', function(e){
if(valName.value !== ''){
valName.nextElementSibling.textContent = '';
valName.className = '';
} else {
e.preventDefault();
valName.nextElementSibling.textContent = errorMessages[0];
valName.className = 'errorborder';
return false;
}
if(valEmail.value.indexOf('@') != -1 && this.value.indexOf('.') != -1){
valEmail.nextElementSibling.textContent = '';
valEmail.className = '';
} else {
e.preventDefault();
valEmail.nextElementSibling.textContent = errorMessages[1];
valEmail.className = 'errorborder';
return false;
}
});

非常感谢!

最佳答案

您必须删除您的返回 - 否则代码将在那里停止。我还将代码移至函数中而不是复制。

    const form = document.getElementsByTagName('form')[0];
let errorMessages = [
"please fill in your name here",
"please, fill in your email correct here",

];

const reg = /^\d+$/;

function isEmailValid(email){
return email.indexOf('@') != -1 && email.indexOf('.') != -1;
}

function isNameValid(name){
return name !== ''
}

function setErrorMessage(el, errorMessage){
el.nextElementSibling.textContent = errorMessage;
el.className = 'errorborder';
}

function clearError(el){
el.nextElementSibling.textContent = '';
el.className = '';
}

form.addEventListener('submit', function(e){
var validName = isNameValid(valName.value);
var validEmail = isEmailValid(valEmail.value);

if(!validName){
setErrorMessage(valName, errorMessages[0]);
}else{
clearError(valName);
}

if(!validEmail){
setErrorMessage(valEmail, errorMessages[1]);
}else{
clearError(valEmail);
}

if(!validName || !validEmail) {
e.preventDefault();
return false;
}
})

关于javascript - 如何使用javascript显示提交时的所有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884724/

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