Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Submit button not working with JS validation

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 class="container">
      <form action="create-lead.php" id="apply" class="form" method="POST">
        <div class="form-field">
          <label for="firstName">First Name</label>
          <input type="text" name="firstName" id="firstName" id="firstName">
          <small></small>
        </div>
        <div class="form-field ">
          <label for="lastName">Last Name</label>
          <input type="text" name="lastName" id="lastName" id="lastName">
          <small></small>
        </div>
        <div class="form-field">
          <label for="email">Email</label>
          <input type="text" name="email" id="email">
          <small></small>
        </div>
        <div class="form-field">
          <label for="telephone">Telephone</label>
          <input type="text" name="telephone" id="telephone">
          <small></small>
        </div>
        <label for="buyerType">Application Type</label>
        <select class="secondary" 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 class="form-field">
          <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 class="form-field">
          <input class="outline " type="submit" name="appy" id="apply">
          <input class="outline secondary" 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading