gs-rp gs-rp - 5 months ago 10
Javascript Question

how to stop js execution with function inside another function

I'm trying to stop the js execution if the validate function returns false. However, if it's false, the script doesn't stop and I can se the message "This will run??" - Would someone give me a hint as to why calling the

validate()
function inside
submit()
doesn't work? What's wrong here? Thanks in advance.

// validate name
function validate(name){
if(name.length < 1){
console.log('false - length: ' + name.length);
return false;
}
}

// submit function
function submit(){
var name = '';

// if name is empty, the script should stop.
validate(name);

console.log("This will run??");
return true;
}

submit();

Answer
function validate(name){
  if(name.length < 1){
      console.log('false - length: ' + name.length);
      return false;
    }
  return true;
}

your validate function should return true (otherwise it returns undefined, which is falsy)

function submit(){
    var name = '';

  // if name is empty, the script should stop.
  if(validate(name)) {
    console.log("This will run??");
    return true;
  } else {
    return false;
  }
}
Comments