views:

47

answers:

4

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.

+4  A: 

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

David Hedlund
Agreed with David
Amit
I tried this and it does stop the functions from running if it false. However, now nothing happens if it is true..
zac
I got it to work by creating an else statement in the email validation and moving the hide/show functions up there.
zac
To get it to work how it is currently you'd need to add `return true` to the end of your validate function.
Jake
A: 

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

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

hideFormOne();
showPartTwo();
return false;
BoltClock
A: 

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.

Tarski
A: 

change your validate function to return true, if valid.

then:

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