简体   繁体   English

停止运行javascript函数

[英]Stop javascript functions from running

I have a few validations happening in the first step of a form. 我在表单的第一步中进行了一些验证。

When the next button is clicked, an age verification is run, if it is true then it runs three functions. 单击下一个按钮时,将运行年龄验证,如果为真,则它将运行三个功能。

function checkAge(form)
{ 
  return false;
}

else {
  validate('theForm','email');
  hideFormOne();
  showPartTwo();
  return false;
};

and the function is 而功能是

function validate(form_id,email){
  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
  var address = document.forms[form_id].elements[email].value;
  if(reg.test(address) == false) {
    alert('Invalid Email Address');      
    return false;
  }
}
function hideFormOne(container1)
{
  document.getElementById('container1').style.display='none';
}
function showPartTwo(container2)
{
  document.getElementById('container2').style.display='block';
}

My problem is, if the email is invalid, the alert pops up, but then when that is closed it continues to run the hide and show functions. 我的问题是,如果电子邮件无效,则会弹出警报,但是当该电子邮件关闭时,它将继续运行隐藏和显示功能。 I need it to only run the hide/show functions if the email is valid. 如果电子邮件有效,我只需要运行隐藏/显示功能。

Since your validate function returns true or false, you can use that value to decide what to do after the function has executed. 由于您的validate函数返回true或false,因此您可以使用该值来确定函数执行后的处理方式。

if(validate('theForm', 'email')) {
   hideFormOne();
   showPartTwo();
}

The above is a terse way of writing 以上是一种简洁的写作方式

var isValid = validate('theForm', 'email');
if(isValid) {
   hideFormOne();
   showPartTwo();
}

... where isValid gets the value that is returned from validate ...其中isValid获取从validate返回的值

Check if validate() returns false, then return false from the calling function: 检查validate()返回false,然后从调用函数中返回false:

if (!validate('theForm','email'))
{
    return false;
}

hideFormOne();
showPartTwo();
return false;

Then change your logic in this part of the code to take into account the return value of validate 然后在代码的这一部分中更改您的逻辑,以考虑validate的返回值

if (validate('theForm','email')) {
    hideFormOne();
    showPartTwo();
}
return false;

}; };

You will also need to change validate to return true if the e-mail address is valid. 如果电子邮件地址有效,您还需要更改validate以返回true

change your validate function to return true, if valid. 更改您的validate函数以返回true(如果有效)。

then: 然后:

else {
  if validate('theForm','email') {
    hideFormOne();
    showPartTwo();
  };
  return false;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM