2 回答
TA贡献1864条经验 获得超6个赞
有很多代码重复。不同字段的多个验证函数具有共同的代码,只是函数名称发生变化。
相反,您可以创建一个函数数组 i:econst validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];
然后调用应用循环的函数。仅当满足条件时, withspan类error才会被删除。required
const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];
validationFunctions.forEach((fun, i) => {
if(!fun(theForm[i])) {
theForm[i].style.borderColor = "#990000";
stopSubmit = true;
} else {
document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";
}
});
window.onload = function() {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function(event) {
event.preventDefault();
let stopSubmit = false;
const validationFunctions = [checkFirstName, checkLastName, checkEmail, checkPhone];
validationFunctions.forEach((fun, i) => {
if (!fun(theForm[i])) {
theForm[i].style.borderColor = "#990000";
stopSubmit = true;
} else { document.querySelector(`#${theForm[i].id}`).nextElementSibling.style.display = "none";
}
});
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.";
}
}
if (input.nextElementSibling.tagName !== 'SPAN') {
renderErrorMessage(input, errorMessage);
}
return errorMessage === "";
}
function checkLastName(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 last name.";
}
if (!inputValue.match(characters)) {
errorMessage = "Special characters detected. Please write your last name.";
}
}
if (input.nextElementSibling.tagName !== 'SPAN') {
renderErrorMessage(input, errorMessage);
}
return errorMessage === "";
}
function checkEmail(input) {
let emailValue = input.value,
errorMessage = "";
let regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailValue.match(regex)) {
errorMessage = "Not a valid email address.";
}
if (emailValue === "") {
errorMessage = "This field is empty.";
}
if (input.nextElementSibling.tagName !== 'SPAN') {
renderErrorMessage(input, errorMessage);
}
return errorMessage === "";
}
function checkPhone(input) {
let phoneValue = input.value,
errorMessage = "";
let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
if (!phoneValue.match(regex)) {
errorMessage = "Not a valid UK phone number.";
}
if (isNaN(phoneValue)) {
errorMessage = "No numbers detected. Please write a UK phone number.";
}
if (phoneValue === "") {
errorMessage = "This field is empty.";
}
if (input.nextElementSibling.tagName !== 'SPAN') {
renderErrorMessage(input, errorMessage);
}
return errorMessage === "";
}
function renderErrorMessage(selectedElem, errorMessage) {
let errorElem = document.createElement("span");
errorElem.setAttribute("class", "error");
let errorText = document.createTextNode(errorMessage);
errorElem.appendChild(errorText);
selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
return selectedElem;
}
label,
button {
display: block;
margin: 10px 0 5px 0;
}
input,
button {
padding: 8px;
width: 393px;
font-size: 16px;
}
body,
button {
font-family: Arial, sans-serif;
}
.error {
color: #FFF;
display: block;
margin: 0 0 15px 0;
background: #990000;
padding: 5px 3px 5px 5px;
width: 405px;
line-height: 25px;
}
.hide {
display: none;
/* background: none; */
}
<form id="form" action="test3success.html" novalidate="novalidate">
<label for="firstName">First Name (required)</label>
<input id="firstName" type="text" name="text" required>
<label for="lastName">Last Name (required)</label>
<input id="lastName" type="text" name="text" required>
<label for="email">Email (required)</label>
<input id="email" type="email" required>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="tel" required>
<button type="submit">Submit</button>
</form>
TA贡献1828条经验 获得超3个赞
使用一个类
通过最少的更改,我在错误时添加类并从所有必填字段中删除该类
添加了代码
theForm[X].classList.add("errorBorder")
和
const req = document.querySelectorAll("[required]")
for (let i=0;i<req.length;i++) {
req[i].classList.remove("errorBorder")
}
我还会在错误跨度上切换类。
window.onload = function() {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function(event) {
let stopSubmit = false;
cleanUpErrors();
if (!checkFirstName(theForm[0])) {
theForm[0].classList.add("errorBorder")
stopSubmit = true;
}
if (!checkLastName(theForm[1])) {
theForm[1].classList.add("errorBorder")
stopSubmit = true;
}
if (!checkEmail(theForm[2])) {
theForm[2].classList.add("errorBorder")
stopSubmit = true;
}
if (!checkPhone(theForm[3])) {
theForm[3].classList.add("errorBorder")
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 === "";
}
function checkLastName(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 last name.";
}
if (!inputValue.match(characters)) {
errorMessage = "Special characters detected. Please write your last name.";
}
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
function checkEmail(input) {
let emailValue = input.value,
errorMessage = "";
let regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailValue.match(regex)) {
errorMessage = "Not a valid email address.";
}
if (emailValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
function checkPhone(input) {
let phoneValue = input.value,
errorMessage = "";
let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
if (!phoneValue.match(regex)) {
errorMessage = "Not a valid UK phone number.";
}
if (isNaN(phoneValue)) {
errorMessage = "No numbers detected. Please write a UK phone number.";
}
if (phoneValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
function renderErrorMessage(selectedElem, errorMessage) {
let errorElem = document.createElement("span");
errorElem.setAttribute("class", "error");
let errorText = document.createTextNode(errorMessage);
errorElem.appendChild(errorText);
selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
return selectedElem;
}
function cleanUpErrors() {
let indicator = document.getElementsByTagName("span");
for (let i = 0; i < indicator.length; i++) {
indicator[i].setAttribute("class", "hide");
}
const req = document.querySelectorAll("[required]")
for (let i=0;i<req.length;i++) {
req[i].classList.remove("errorBorder")
}
}
label,
button {
display: block;
margin: 10px 0 5px 0;
}
input,
button {
padding: 8px;
width: 393px;
font-size: 16px;
}
body,
button {
font-family: Arial, sans-serif;
}
.error {
color: #FFF;
display: block;
margin: 0 0 15px 0;
background: #990000;
padding: 5px 3px 5px 5px;
width: 405px;
line-height: 25px;
}
.hide {
display: none;
background: none;
}
.errorBorder {
border-color:#990000
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Personal Information Form</title>
<script src="scripts/test5.js"></script>
<link rel="stylesheet" href="css/test.css">
</head>
<body>
<form id="form" action="test3success.html" novalidate="novalidate">
<label for="firstName">First Name (required)</label>
<input id="firstName" type="text" name="text" required>
<label for="lastName">Last Name (required)</label>
<input id="lastName" type="text" name="text" required>
<label for="email">Email (required)</label>
<input id="email" type="email" required>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="tel" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
实际上,由于这些字段被标记为必填,因此您可以将自定义消息添加到 HTML5 验证中并让它处理所有内容
工作正在进行中:
const letters = /^[a-zA-Z]+$/,
const characters = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;
const emailRe = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const phoneRe = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
window.addEventListener("load", function() {
var elements = document.querySelectorAll("input[required]");
for (let i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
};
}
})
function checkName(input) {
let inputValue = input.value,
errorMessage = "",
if (inputValue.length < 3) {
this.setCustomValidity("This field has less than 3 characters.");
}
if (!inputValue.match(letters)) {
this.setCustomValidity("Numbers detected. Please write a name.");
}
if (!inputValue.match(characters)) {
this.setCustomValidity("Special characters detected. Please write a name.");
}
}
function checkEmail(input) {
let emailValue = input.value,
errorMessage = "";
if (!emailValue.match(emailRe)) {
errorMessage = "Not a valid email address.";
}
if (emailValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
function checkPhone(input) {
let phoneValue = input.value,
errorMessage = "";
if (!phoneValue.match(phoneRe)) {
errorMessage = "Not a valid UK phone number.";
}
if (isNaN(phoneValue)) {
errorMessage = "No numbers detected. Please write a UK phone number.";
}
if (phoneValue === "") {
errorMessage = "This field is empty.";
}
renderErrorMessage(input, errorMessage);
return errorMessage === "";
}
function renderErrorMessage(selectedElem, errorMessage) {
let errorElem = document.createElement("span");
errorElem.setAttribute("class", "error");
let errorText = document.createTextNode(errorMessage);
errorElem.appendChild(errorText);
selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
return selectedElem;
}
label,
button {
display: block;
margin: 10px 0 5px 0;
}
input,
button {
padding: 8px;
width: 393px;
font-size: 16px;
}
body,
button {
font-family: Arial, sans-serif;
}
.error {
color: #FFF;
display: block;
margin: 0 0 15px 0;
background: #990000;
padding: 5px 3px 5px 5px;
width: 405px;
line-height: 25px;
}
.hide {
display: none;
background: none;
}
.errorBorder {
border-color:#990000
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Personal Information Form</title>
<script src="scripts/test5.js"></script>
<link rel="stylesheet" href="css/test.css">
</head>
<body>
<form id="form" action="test3success.html" novalidate="novalidate">
<label for="firstName">First Name (required)</label>
<input id="firstName" type="text" name="text" required>
<label for="lastName">Last Name (required)</label>
<input id="lastName" type="text" name="text" required>
<label for="email">Email (required)</label>
<input id="email" type="email" required>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="tel" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
- 2 回答
- 0 关注
- 88 浏览
添加回答
举报