我有一个项目,我需要创建一个表单来验证每个输入,如果出现错误,它将显示消息。如果没有错误,则不会显示任何消息。
我已经做到了,但每次没有错误时,我似乎无法删除span标签的红色背景。
在cleanUpErrors()
我尝试使用indicator[i].remove();
但indicator[i].setAttribute("class", "hide");
它们都不起作用。
一旦没有错误消息,就不应该有任何红色背景。
window.onload = function () {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function (event) {
let stopSubmit = false;
cleanUpErrors();
if (!checkFirstName(theForm[0])) {
theForm[0].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkLastName(theForm[1])) {
theForm[1].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkEmail(theForm[2])) {
theForm[2].style.borderColor = "#990000";
stopSubmit = true;
}
if (!checkPhone(theForm[3])) {
theForm[3].style.borderColor = "#990000";
stopSubmit = true;
}
if (stopSubmit) {
event.preventDefault();
}
}, false)
}
function checkFirstName(input) {
let inputValue = input.value, errorMessage = "", letters = /^[a-zA-Z]+$/, characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;
if (inputValue === null || inputValue === "") {
errorMessage = "This field is empty.";
}
if (inputValue !== "") {
if (inputValue.length < 3) {
errorMessage = "This field has less than 3 characters.";
}
if(!inputValue.match(letters)){
errorMessage = "Numbers detected. Please write your first name.";
}
if(!inputValue.match(characters)){
errorMessage = "Special characters detected. Please write your first name.";
}
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
慕尼黑的夜晚无繁华
子衿沉夜
相关分类