Home > Software design >  preventDefault() cause problem on validating the form
preventDefault() cause problem on validating the form

Time:09-17

the code below was written to validate simple html form with JavaScript and preventDefault() method means that if the required fields are empty then stop form submission and display error or otherwise submit the form if the required fields are not empty.

The problem comes when I click the submit button the form isn't working. Can anyone please help me to solve the problem?

let form = document.getElementById("signUp");
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;

function validateForm() {
  if (uname == " ") {
    alert("Name is Empty");
  } else if (uemail == " ") {
    alert("Email is Empty");
    return false;
  }
  return true;
}
form.addEventListener("submit", function(e) {
  e.preventDefault();
  validateForm();
});
<form id="signUp" name="myForm">
  Name: <input type="text" name="uname" id="userName">
  <br> Email: <input type="email" name="email" id="userEmail">
  <button type="submit">sign up</button>
</form>

CodePudding user response:

With e.preventDefault() you say that the form should not be submitted. So you only want to call if in case the validation returns false.

Besides that, your uname and uemail is set before the form is submitted. So it won't contain the state of the input fields at the time the form is submitted. You have to move them into your validateForm function.

let form = document.getElementById("signUp");

function validateForm() {
  let uname = document.forms["myForm"]["userName"].value;
  let uemail = document.forms["myForm"]["userEmail"].value;
  if (uname == " ") {
    alert("Name is Empty");
  } else if (uemail == " ") {
    alert("Email is Empty");
    return false;
  }
  return true;
}
form.addEventListener("submit", function(e) {
  if (!validateForm()) {
    e.preventDefault();
  }
});
<form id="signUp" name="myForm">
  Name: <input type="text" name="uname" id="userName">
  <br> Email: <input type="email" name="email" id="userEmail">
  <button type="submit">sign up</button>
</form>

And uname == " " does not test if the name is empty. It tests if it consists of one character that is a space. The same is for uemail == " ". You probably looking for uname.trim() == ""

As you need to verify the data on the server anyways. And in some way need to display an error if the validation fails on the server side.

It is often sufficient to rely on the HTML solutions to verify the form data (if the browser support is decent enough even if it is not complete).

Something like this:

.error {
  display: none;
}

input:not(:placeholder-shown):invalid  .error {
  display: block;
}
<form id="signUp" name="myForm">
  Name: <input type="text" name="uname" id="userName" placeholder="Name" pattern="^(?!^  $)([\w -&] )$" required>
  <div >Name must not be empty</div>
  <br> Email: <input type="email" name="email" id="userEmail" placeholder="Email" required>
  <div >Email must be valid</div>
  <button type="submit">sign up</button>
</form>

CodePudding user response:

const form = document.getElementById("signUp");
form.addEventListener("submit", (e) => {
  e.preventDefault();
  if(validate()) {
    form.submit()  
  }
});

const validate = () => {
   const name = document.querySelector("#userName");
   const email = document.querySelector("#email");
   let hasError = false;
   
   if(!(name.value && name.value.length > 4)) {
      const nameErr = document.querySelector("#user-name-error");
      nameErr.textContent = "Name is required";
      hasError = true;
   }
   
   if(!(name.value && name.value.length > 0)) {
      const emailErr = document.querySelector("#user-email-error");
      emailErr.textContent = "Email is required";
      hasError = true;
   }
   
   return !hasError;
};
<form id="signUp" name="myForm">
  <div >
    <label for="userName">Name: </label>
    <input type="text" name="uname" id="userName" />
    <p id="user-name-error" style="color: red;"></p>
  </div>
  <div >
    <label for="userEmail">Email: </label>
    <input type="email" name="email" id="email" />
    <p id="user-email-error" style="color: red;"></p>
  </div>
  <button type="submit">sign up</button>
</form>

CodePudding user response:

<form id="signUp" name="myForm">
  <div >
    <label for="userName">Name: </label>
    <input type="text" name="uname" id="userName" required minlength="4"/>
  </div>
  <div >
    <label for="userEmail">Email: </label>
    <input type="email" name="email" id="email" required pattern="[^@]*@[^.]*\..*"/>
  </div>
  <button type="submit">sign up</button>
</form>

This is an example using only html, it is only for your use case of course if you want to add more complexe validation use javascript

  • Related