Home > Blockchain >  Form check prevent from submiting even when everything is ok
Form check prevent from submiting even when everything is ok

Time:03-07

i have a problem with my form, i ran it through the form checker and even when everything is successful it still won't submit. i tried to change it a lot of times and im not sure how to keep the code like that instead of one function that will return on form submit.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
const genderSelected = document.getElementById('select');
//Show input error messages
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

//show success colour
function showSucces(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
  const re = /^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSucces(input)
  } else {
    showError(input, 'Email is not invalid');
  }
}


//checkRequired fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`)
    } else {
      showSucces(input);
    }
  });
}


//check input Length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(input, `${getFieldName(input)} must be at least ${min} characters`);
  } else if (input.value.length > max) {
    showError(input, `${getFieldName(input)} must be les than ${max} characters`);
  } else {
    showSucces(input);
  }
}

//get FieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase()   input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

//check if selected a gender
function checkSelect(option) {
  if (select.value)
    showSucces(option);
  else
    showError(option, 'Please select a gender');
}



//Event Listeners
form.addEventListener('submit', function(e) {
  e.preventDefault();

  checkRequired([username, email, password, password2, genderSelected]);
  checkLength(username, 3, 15);
  checkLength(password, 6, 25);
  checkEmail(email);
  checkPasswordMatch(password, password2);
  checkSelect(genderSelected);
});
@import url('https://fonts.googleapis.com/css?family=Open Sans&display=swap');
 :root {
  --succes-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

.wrapper {
  width: 400px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 25px;
  margin: 8% auto 0;
  position: relative;
}

.container {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

.form-control {
  margin-bottom: 10px;
  padding-bottom: 20px;
  position: relative;
}

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 14px;
}

.form-control input:focus {
  outline: 0;
  border-color: #777;
}

.form-control.success input {
  border-color: var(--succes-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
  width: 100%;
}

form {
  border: 0px solid black;
  display: inline-block;
  text-align: left;
}

body {
  margin: 50px 0px;
  padding: 0px;
  text-align: center;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: inline;
  resize: horizontal
}

label,
input[type="text,password,date"] {
  display: block;
  width: 150px;
  float: left;
  margin-bottom: 10px;
}

input[type="radio"] {
  display: block;
  width: 25px;
  float: left;
  margin-bottom: 10px;
}

label {
  text-align: right;
  width: 75px;
  padding-right: 20px;
}

br {
  clear: left;
}

h1 {
  color: black;
  text-align: center;
  font-size: xx-large;
}

.button {
  text-align: center;
  margin: auto;
  display: inline-block;
  padding: 5px 15px;
  font-size: 18px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: black;
  background-color: white;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: black;
  color: white;
}

.button:active {
  background-color: black;
  color: white;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

p {
  font-family: verdana;
  font-size: 20px;
}

#wrapper {
  width: 30%;
  margin: 50px auto;
  padding: 50px;
  background: #D7FBFF;
}

.textInput {
  border: none;
  height: 28px;
  margin: 2px;
  border: 1px solid #6B7363;
  font-size: 1.2em;
  padding: 5px;
  width: 95%;
}

.textInput:focus {
  outline: none;
}

.btn {
  width: 98.6%;
  border: none;
  margin-top: 5px;
  color: white;
  background-color: #3b5998;
  border-radius: 5px;
  padding: 12px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
  border-right: 1px solid #bbb;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

output {
  display: inline;
}

.customizedBox {
  border: 1px solid #111;
  width: 500px;
  height: 400px;
}

select {
  width: 280px;
  height: 40px;
  padding: 10px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  border: none;
}
<div >
  <ul>
    <li><a href="HomePage.aspx">Home</a></li>
    <li><a href="MemesOverTheYears.aspx">Memes Over The Years</a></li>
    <li><a href="Profile.html">Profile</a></li>
    <li><a href="About.aspx">About</a></li>
  </ul>
</div>
<!-- partial:index.partial.html -->
<div >
  <div >
    <form id="form" >
      <h2>Register With Us</h2>
      <div >
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Enter Username">
        <small>Error Message</small>
      </div>
      <div >
        <label for="email">Email</label>
        <input type="text" id="email" placeholder="Enter email">
        <small>Error Message</small>
      </div>
      <div >
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter password">
        <small>Error Message</small>
      </div>
      <div >
        <label for="password2">Confirm Password</label>
        <input type="password" id="password2" placeholder="Enter password again">
        <small>Error Message</small>
      </div>
      <div >
        <label for="gender">Gender</label> <br/>
        <select id="select">
          <option value="">Choose an option</option>
          <option value="Male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <small>Error Message</small>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</div>
<br /><br /><br /><br />
<span>Allready have an account?<a href="LogIn.aspx">Log In</a></span>

CodePudding user response:

Here is the simplest fix for you always blocking the submission with preventDefault

  if (document.querySelectorAll(".error").length > 0) e.preventDefault();

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
const genderSelected = document.getElementById('select');
//Show input error messages
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

//show success colour
function showSucces(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
  const re = /^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSucces(input)
  } else {
    showError(input, 'Email is not invalid');
  }
}


//checkRequired fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`)
    } else {
      showSucces(input);
    }
  });
}


//check input Length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(input, `${getFieldName(input)} must be at least ${min} characters`);
  } else if (input.value.length > max) {
    showError(input, `${getFieldName(input)} must be les than ${max} characters`);
  } else {
    showSucces(input);
  }
}

//get FieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase()   input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

//check if selected a gender
function checkSelect(option) {
  if (select.value)
    showSucces(option);
  else
    showError(option, 'Please select a gender');
}



//Event Listeners
form.addEventListener('submit', function(e) {
  checkRequired([username, email, password, password2, genderSelected]);
  checkLength(username, 3, 15);
  checkLength(password, 6, 25);
  checkEmail(email);
  checkPasswordMatch(password, password2);
  checkSelect(genderSelected);
  if (document.querySelectorAll(".error").length > 0) e.preventDefault();

  
});
@import url('https://fonts.googleapis.com/css?family=Open Sans&display=swap');
 :root {
  --succes-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

.wrapper {
  width: 400px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 25px;
  margin: 8% auto 0;
  position: relative;
}

.container {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

.form-control {
  margin-bottom: 10px;
  padding-bottom: 20px;
  position: relative;
}

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 14px;
}

.form-control input:focus {
  outline: 0;
  border-color: #777;
}

.form-control.success input {
  border-color: var(--succes-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
  width: 100%;
}

form {
  border: 0px solid black;
  display: inline-block;
  text-align: left;
}

body {
  margin: 50px 0px;
  padding: 0px;
  text-align: center;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: inline;
  resize: horizontal
}

label,
input[type="text,password,date"] {
  display: block;
  width: 150px;
  float: left;
  margin-bottom: 10px;
}

input[type="radio"] {
  display: block;
  width: 25px;
  float: left;
  margin-bottom: 10px;
}

label {
  text-align: right;
  width: 75px;
  padding-right: 20px;
}

br {
  clear: left;
}

h1 {
  color: black;
  text-align: center;
  font-size: xx-large;
}

.button {
  text-align: center;
  margin: auto;
  display: inline-block;
  padding: 5px 15px;
  font-size: 18px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: black;
  background-color: white;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: black;
  color: white;
}

.button:active {
  background-color: black;
  color: white;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

p {
  font-family: verdana;
  font-size: 20px;
}

#wrapper {
  width: 30%;
  margin: 50px auto;
  padding: 50px;
  background: #D7FBFF;
}

.textInput {
  border: none;
  height: 28px;
  margin: 2px;
  border: 1px solid #6B7363;
  font-size: 1.2em;
  padding: 5px;
  width: 95%;
}

.textInput:focus {
  outline: none;
}

.btn {
  width: 98.6%;
  border: none;
  margin-top: 5px;
  color: white;
  background-color: #3b5998;
  border-radius: 5px;
  padding: 12px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
  border-right: 1px solid #bbb;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

output {
  display: inline;
}

.customizedBox {
  border: 1px solid #111;
  width: 500px;
  height: 400px;
}

select {
  width: 280px;
  height: 40px;
  padding: 10px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  border: none;
}
<div >
  <ul>
    <li><a href="HomePage.aspx">Home</a></li>
    <li><a href="MemesOverTheYears.aspx">Memes Over The Years</a></li>
    <li><a href="Profile.html">Profile</a></li>
    <li><a href="About.aspx">About</a></li>
  </ul>
</div>
<!-- partial:index.partial.html -->
<div >
  <div >
    <form id="form" >
      <h2>Register With Us</h2>
      <div >
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Enter Username">
        <small>Error Message</small>
      </div>
      <div >
        <label for="email">Email</label>
        <input type="text" id="email" placeholder="Enter email">
        <small>Error Message</small>
      </div>
      <div >
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter password">
        <small>Error Message</small>
      </div>
      <div >
        <label for="password2">Confirm Password</label>
        <input type="password" id="password2" placeholder="Enter password again">
        <small>Error Message</small>
      </div>
      <div >
        <label for="gender">Gender</label> <br/>
        <select id="select">
          <option value="">Choose an option</option>
          <option value="Male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <small>Error Message</small>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</div>
<br /><br /><br /><br />
<span>Allready have an account?<a href="LogIn.aspx">Log In</a></span>

CodePudding user response:

You call e.preventDefault() unconditionally.

This means, that whatever your code does, you will never submit the form (the default action)

Wrap the prevent default in an if statement and execute it only if the validation fails.

  • Related