我在删除表单验证中的自定义错误消息时遇到了困难。每次我提交表单时,消息都会复制,如果字段有效,我不知道如何删除它们。我很高兴听到你的回答!
form.onsubmit = function valCheck(ev) {
ev.preventDefault();
var fields = ev.target
console.log(fields);
var nameVal = /^[a-zA-ZäÄüÜöÖáàiìíéèóòúù `´,.'-]+$/;
var emailVal = /[^\s@]+@[^\s@]+\.[^\s@]+/;
for (var i = 0; i < formLen; i++) {
var errorText = document.createElement('P');
div[i].appendChild(errorText);
console.log(errorText);
if (fields[i].value === "") {
errorText.innerHTML = "This field should not be empty"
}
else if (fields[i].type == "text") {
if (!fields[i].value.match(nameVal)) {
errorText.innerHTML = "no numbers allowed"
}
}
else if (fields[i].type == "email") {
if (!fields[i].value.match(emailVal)) {
errorText.innerHTML = "insert a valid adress"
}
}
else if (fields[i].type == "checkbox") {
if (!fields[i].checked) {
errorText.innerHTML = "checkbox need to be checked"
}
}
else if (fields[i].type == "radio") {
if (fields[i].checked) {
errorText.innerHTML = "you need to select something"
}
}
}
}