Using the outcome of a function in another function

54 views Asked by At

I have created 3 functions to cilentside validate a form for its name, email, and website, I would like to create a 4th function that checks if the outcome of the 3 first functions is true, we submit the form, if the outcome of any of them is false, the form doesn't get submitted. Below is my attempt for the JavaScript. The purpose of this question is to learn how to use a 4th function to check the other 3 functions returns.

//validating name, email, website:

function nameValidation() {
  var valid = true;
  var name = document.getElementById("name1").value;
  var validname = /^[a-zA-Z\s]*$/;

  if (name == "") {
    document.getElementById("errorMsg2").innerHTML = "* Name is required";
    valid = false;
  } else if (name.match(validname)) {
    valid = true;
  } else {
    document.getElementById("errorMsg2").innerHTML = "* Only letters and white spaces allowed";
    valid = false;
  }

  return valid;
}

function emailValidation() {
  var valid = true;
  var validEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  var email = document.getElementById("email1").value;

  if (email == "") {
    document.getElementById("errorMsg3").innerHTML = "* Email is required";
    valid = false;
  } else if (email.match(validEmail)) {
    valid = true;
  } else {
    document.getElementById("errorMsg3").innerHTML = "*Please enter a valid email.";
    valid = false;
  }

  return valid;

}

function websiteValidation() {
  var valid = true;
  var validWebsite = /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i;
  var website = document.getElementById("website1").value;

  if (website == "" || website.match(validWebsite)) {
    valid = true;
  } else {
    document.getElementById("errorMsg4").innerHTML = "* Website is required";
    valid = false;
  }

  return valid;
}



// function for form submission:
function formSubmit() {
  if (nameValidation() == true && emailValidation() == true && websiteValidation() == true) {
    return true;
  } else {
    return false;
  }
}

document.getElementById("submit").addEventListener("click", () => {
  console.log("Final result:", formSubmit());
});
<div>
  <div id="errorMsg2"></div>
  <input type="text" id="name1" />
</div>
<div>
  <div id="errorMsg3"></div>
  <input type="text" id="email1" />
</div>
<div>
  <div id="errorMsg4"></div>
  <input type="text" id="website1" />
</div>
<div>
  <input type="submit" id="submit" />
</div>

1

There are 1 answers

1
Niet the Dark Absol On

Delete all of the JavaScript. This is the only HTML you need:

<input type="text" id="name1" pattern="[a-zA-Z\s]+" title="Letters and spaces only" required />
<input type="email" id="email1" required />
<input type="url" id="website1" required />
<input type="submit" id="submit" />

HTML5 Form validation has been around for a very long time at this point.