简体   繁体   中英

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.

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

Check if validate() returns false, then return false from the calling function:

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

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.

change your validate function to return true, if valid.

then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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