0

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.

2
  • 1
    form.addEventListener('submit', function(e) { e.preventDefault(); The preventDefault() blocks the automatic submitting of the form, so you have time to validate it with JS. This does mean you have to submit the form manually after that. You cannot block the submit to do JS and then expect it to still submit after you're done with JS, you have to code that yourself in the if (isFormValid) { block. Commented Jun 27, 2022 at 14:15
  • so would I just put document.getElementById("apply").submit, within that block? Commented Jun 27, 2022 at 14:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.