gpt4 book ai didi

javascript - 在当前 JavaScript 代码中添加另一个函数?

转载 作者:行者123 更新时间:2023-11-28 04:42:47 27 4
gpt4 key购买 nike

有人可以告诉我如何将下面的 JavaScript(函数 validateEmail() 添加到我已经创建的 JavaScript(函数 validateForm() 中)吗?我需要将两者合而为一。我所做的是创建一个 JavaScript 来创建错误消息,那么如果电子邮件字段输入错误,我的新代码会创建一条错误消息。较长的 JavaScript 需要较短的 JavaScript。我是否只需添加一个 else if、if 比?我是 JavaScript 新手。谢谢那些帮助。

function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}

新的 JavaScript

function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^@]+@[^@]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}

最佳答案

您的最终函数应如下所示:

function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}

ret &= validateEmail();

var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}

// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^@]+@[^@]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}

编辑

如果您不能(或不想)更改 validateForm函数包含对 validateEmail 的调用那么您可以以 onsubmit 的形式指定这两个函数

onsubmit="return validateForm() && validateEmail()"

关于javascript - 在当前 JavaScript 代码中添加另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43624313/

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