gpt4 book ai didi

javascript - 有点优雅的表单验证

转载 作者:行者123 更新时间:2023-11-29 19:40:51 24 4
gpt4 key购买 nike

目前我有以下代码,我一直听说我不应该使用 alert 函数,它太过时了等等。
除了 alert,我还能用什么?

document.getElementById("practiseForm").onsubmit = function() {
if(document.getElementById("fname").value.trim() === ""){
alert("First Name Field Cannot Be Blank");
allowsubmit = false;
}
if(document.getElementById("lname").value.trim() === ""){
alert("Last Name Field Cannot Be Blank");
allowsubmit = false;
}
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
alert("Invalid Email address");
return false;
}
}

Fiddle

最佳答案

我更新了您的 fiddle 以提供内联错误消息的示例:

document.getElementById("practiseForm").onsubmit = function() {
var fName = document.getElementById("fname");
var fNameError = fName.nextElementSibling;
var lName = document.getElementById("lname");
var lNameError = lName.nextElementSibling;
if(fName.value.trim() === ""){
fNameError.innerHTML = "First Name Field Cannot Be Blank";
allowsubmit = false;
} else {
fNameError.innerHTML = "";
}
if(document.getElementById("lname").value.trim() === ""){
lNameError.innerHTML = "Last Name Field Cannot Be Blank";
allowsubmit = false;
} else {
lNameError.innerHTML = "";
}
var email = document.getElementById('email');
var emailError = email.nextElementSibling;
var emailRegEx = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
emailError.innerHTML = "Error in e-mail format";
return false;
} else {
emailError.innerHTML = "";
}
}

http://jsfiddle.net/Ty8AQ/10/

关于javascript - 有点优雅的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117854/

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