Search code examples
javascriptformsvalidation

Javascript form validation hindering data insertion to PHP


I created form validation in Javascript and its working but the data can’t be inserted to the backend PHP. They can only insert data when they comment out e.preventDefault(), so my client side validation doesn’t work but there's work and the data is inserted. what could be the issue?

this is the javascript code, i also tried ajax and it logged form data as an object so its working. but they were not able to use it.

signupForm.addEventListener('submit', (event) => {
let isValid = true;

    if (firstNameInput.value.trim() === '' || firstNameInput.value.trim().length < 3) {
        displayError(firstNameInput, 'Please enter a valid first name!');
        isValid = false;
    } else {
        hideError(firstNameInput);
    }

    if (lastNameInput.value.trim() === '' || lastNameInput.value.length < 3) {
        displayError(lastNameInput, 'Please enter a valid last name!');
        isValid = false;
    } else {
        hideError(lastNameInput);
    }

    if (!emailIsValid(emailInput.value)) {
        displayError(emailInput, 'Please enter a valid email!');
        isValid = false;
    } else {
        hideError(emailInput);
    }

    if (numberInput.value === '' || numberInput.value.length < 11){
        displayError(numberInput, 'Please enter a valid mobile number!');
        isValid = false;
    } else {
        hideError(numberInput);
    }

    if (passwordInput.value === '' || passwordInput.value.length < 8) {
        displayError(passwordInput, 'Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.');
        isValid = false;
    } else {
        hideError(passwordInput);
    }

    if (countrySelect.value === 'Country*') {
        displayError(countrySelect, 'Please select a country!');
        isValid = false;
    } else {
        hideError(countrySelect);
    }

    if (companyNameInput.value === '') {
        displayError(companyNameInput, 'Please enter your workplace!');
        isValid = false;
    } else {
        hideError(companyNameInput);
    }

if (!isValid) {
    event.preventDefault();
    console.log("Form is not submitted (validation failed)");
} else {
    signupForm.submit();
    console.log("Form is submitted (validation passed)");
}


console.log(isValid)});


function emailIsValid(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function displayError(element, message) {
    const errorParent = element.closest('.input-parent');
    const errorMsg = errorParent.querySelector('.error');

    errorMsg.style.display = 'block';
    errorMsg.textContent = message;
    element.classList.add('is-invalid');
}


function hideError(element) {
    const successParent = element.closest('.input-parent');
    const successMsg = successParent.querySelector('.success');
    const errorParent = element.closest('.input-parent');
    const errorMsg = errorParent.querySelector('.error');

    successMsg.textContent = '';
    successMsg.style.display = 'block';
    errorMsg.style.display = 'none';
    element.classList.remove('is-invalid');
}

any help would be appreciated


Solution

  • Use the build-in form validation instead of creating your own. The form will only submit if all the required (the required attribute) form fields are valid. There is a number of ways that you can validate some value. Here I used the pattern attribute that takes a regular expression as a value to validate against.

    document.forms.signup.addEventListener('invalid', e => {
      e.preventDefault();
      let label = e.target.closest('label');
      label.classList.add('invalid');
    }, true);
    
    document.forms.signup.addEventListener('input', e => {
      let label = e.target.closest('label');
      if (e.target.validity.valid) {
        label.classList.remove('invalid');
      }
    });
    .error {
      font-size: smaller;
      visibility: hidden;
    }
    
    .invalid~.error {
      visibility: visible;
    }
    <form name="signup" action="/signup" method="POST">
      <label>First name: <input type="text" name="firstName" required></label>
      <div class="error">Please enter a your first name</div>
      <label>Last name: <input type="text" name="lastName" required></label>
      <div class="error">Please enter a your last name</div>
      <label>Email: <input type="email" name="email" required></label>
      <div class="error">Please enter a valid email</div>
      <label>Mobile: <input type="text" name="number"
        pattern="[0-9]{6,8}" required></label>
      <div class="error">Please enter a valid mobile number (6-8 didets)</div>
      <label>Password: <input type="password" name="password"
        pattern="[a-zA-Z0-9]{8,20}" required></label>
      <div class="error">Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.</div>
      <label>Country: <select name="country" required>
    <option value="">Select a country</option>
    <option value="1">Country 1</option>
    <option value="2">Country 2</option>
    </select></label>
      <div class="error">Please select a country</div>
      <button>Submit</button>
    </form>