为当前JavaScript代码添加另一个函数?

时间:2017-04-26 03:08:29

标签: javascript

有人可以告诉我如何将我的下面的JavaScript(函数validateEmail()函数添加到我已创建的JavaScript中(函数validateForm()?我需要将2合并为一个。我所做的是创建一个JavaScript来创建错误消息,然后我的新消息会在电子邮件字段输入不正确的情况下创建错误消息。较长的JavaScript需要较短的消息。如果是,我只是添加一个else吗?我是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;
}

2 个答案:

答案 0 :(得分:0)

您的最终功能应如下所示:

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()"

答案 1 :(得分:0)

您的表单验证脚本只需将您的附加功能称为附加测试。

尝试将其添加到主要功能的末尾:

if(!validateEmail()) {
    //  error code
    ret=false;
}
else {
    //  ok
}

return ret;