Home > Back-end >  Submit button not working with JS validation
Submit button not working with JS validation

Time:06-28

const firstNameEl = document.querySelector('#firstName');
const lastNameEl = document.querySelector('#lastName');
const emailEl = document.querySelector('#email');
const telephoneEl = document.querySelector('#telephone');

const form = document.querySelector('#apply');

const checkFirstName = () => {
    let valid = false;

    const firstName = firstNameEl.value.trim();

    if (!isRequired(firstName)) {
        showError(firstNameEl, 'First name cannot be blank');
    } else if (!isFirstNameValid(firstName)) {
        showError(firstNameEl, 'First name must only contain letters');
    } else {
        showSuccess(firstNameEl);
        valid = true;
    };
    return valid;
};

const checkLastName = () => {
    let valid = false;

    const lastName = lastNameEl.value.trim();

    if (!isRequired(lastName)) {
        showError(lastNameEl, 'Last name cannot be blank');
    } else if (!isLastNameValid(lastName)) {

        showError(lastNameEl, 'Last name must only contain letters');

    } else {
        showSuccess(lastNameEl);
        valid = true;
    }
    return valid;
};

const checkEmail = () => {
    let valid = false;
    const email = emailEl.value.trim();
    if (!isRequired(email)) {
        showError(emailEl, 'Email cannot be blank.');
    } else if (!isEmailValid(email)) {
        showError(emailEl, 'Email is not valid.')
    } else {
        showSuccess(emailEl);
        valid = true;
    }
    return valid;
};
const checkTelephone = () => {
    let valid = false;
    const telephone = telephoneEl.value.trim();
    if (!isRequired(telephone)) {
        showError(telephoneEl, 'Telephone field cannot be left blank');
    } else if (!isTelephoneValid(telephone)) {
        showError(telephoneEl, 'Number is not valid')
    } else {
        showSuccess(telephoneEl);
        valid = true;
    }
    return valid;
};

// const accept = () => {
//     if (!document.querySelector('#accept').checked) {
//         showError(accept, 'You must accept the terms to continue')
//     } else {
//         showSuccess(accept);
//         valid = true;
//     }
//     return valid;
// };

const isFirstNameValid = (firstName) => {
    const re = /^[a-zA-Z] $/;
    return re.test(firstName);
};

const isLastNameValid = (lastName) => {
    const re = /^[a-zA-Z] $/;
    return re.test(lastName);
};


const isEmailValid = (email) => {
    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,}))$/;
    return re.test(email);
};

const isTelephoneValid = (telephone) => {
    const re = /^[0-9] $/;
    return re.test(telephone);
};

const isRequired = value => value === '' ? false : true;


const showError = (input, message) => {
    const formField = input.parentElement;
    formField.classList.remove('success');
    formField.classList.add('error');

    const error = formField.querySelector('small');
    error.textContent = message;
};

const showSuccess = (input) => {
    const formField = input.parentElement;

    formField.classList.remove('error');
    formField.classList.add('success');

    const error = formField.querySelector('small');
    error.textContent = '';
}



form.addEventListener('submit', function(e) {
    e.preventDefault();
    //validate fields
    let isFirstNameValid = checkFirstName(),
        isLastNameValid = checkLastName(),
        isEmailValid = checkEmail(),
        isTelephoneValid = checkTelephone();


    let
        isFormValid = isFirstNameValid &&
        isLastNameValid &&
        isEmailValid &&
        isTelephoneValid;

    if (isFormValid) {

    }

});

const debounce = (fn, delay = 500) => {

    let timeoutId;

    return (...args) => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
            fn.apply(null, args)
        }, delay);
    };
};

form.addEventListener('input', debounce(function(e) {
    switch (e.target.id) {
        case 'firstName':
            checkFirstName();
            break;
        case 'lastName':
            checkLastName();
            break;
        case 'email':
            checkEmail();
            break;
        case 'telephone':
            checkTelephone();
            break;
    }
}));
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>DAS Applicant Form</title>
  <link rel="stylesheet" href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
  <style>

  </style>
</head>

<body style="padding:40px">
  <main>

    <h1>Applicant Form</h1>
    <div >
      <form action="create-lead.php" id="apply"  method="POST">
        <div >
          <label for="firstName">First Name</label>
          <input type="text" name="firstName" id="firstName" id="firstName">
          <small></small>
        </div>
        <div >
          <label for="lastName">Last Name</label>
          <input type="text" name="lastName" id="lastName" id="lastName">
          <small></small>
        </div>
        <div >
          <label for="email">Email</label>
          <input type="text" name="email" id="email">
          <small></small>
        </div>
        <div >
          <label for="telephone">Telephone</label>
          <input type="text" name="telephone" id="telephone">
          <small></small>
        </div>
        <label for="buyerType">Application Type</label>
        <select  name="buyerType" id="buyerType">
            <option value="Purchase">Purchase</option>
            <option value="FirstTimeBuyer">First Time Buyer</option>
            <option value="Remortgage">Remortgage</option>
            <option value="RaiseFunds">Raise Funds</option>
          </select>
        <div >
          <label for="accept">
              <input type="checkbox" id="accept" name="accept" value="yes">
              I agree to the terms and conditions <a href="#">See terms</a>
            </label>
          <small></small>
        </div>
        <div >
          <input  type="submit" name="appy" id="apply">
          <input  type="reset" name="reset" id="reset">
        </div>
      </form>
    </div>
    <script src="js/app.js"></script>
  </main>
</body>

</html>

I have a form with an submit button, that was working before I implemented javascript validation, and now the submit button does not submit.

I have looked at other answers but nothing matches my problem. The create-lead.php file works fine as that has been tested numerous times, but there is something in the javascript code that is stopping the submit button from working, but I dont have enough experience working with javascript to work it out.

CodePudding user response:

The cause is the e.preventDefault();, which tells the browser to not execute the submit function.

You can move the e.preventDefault(); to a condition, such as if (!isFormValid) { e.preventDefault(); }, so it will be "prevented" only if the validation fails.

Check the MDN: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

  • Related