skip to Main Content

I’ve been trying to solve this issue with javascript form validations. I’m submitting with a validateForm() function on the form.

I was expecting the form data to be validated when clicking on submit but it just bypasses every validation and submits the form.

this below is my validation function in the script.js file

function validateForm() {
  document
    .getElementById("registrationForm")
    .addEventListener("submit", function (event) {
      const dobInput = document.getElementById("dob").value;
      const state = document.getElementById("state").value;
      const postcode = document.getElementById("postcode").value;
      const firstName = document.getElementById("firstName").value;
      const lastName = document.getElementById("lastName").value;
      const otherSkillsCheckbox = document.getElementById("otherSkills");
      const otherSkillsText = document.getElementById("otherSkillsText").value;
      const errorMessages = document.getElementById("errorMessages");
      errorMessages.textContent = ""; // Clear previous error messages

      // Date of Birth Validation
      const dobRegex = /^(d{2})/(d{2})/(d{4})$/;
      if (!dobRegex.test(dobInput)) {
        errorMessages.textContent += "Invalid date format (dd/mm/yyyy).n";
        event.preventDefault(); // Prevent form submission
      } else {
        const [, day, month, year] = dobRegex.exec(dobInput);
        const dobDate = new Date(`${year}-${month}-${day}`);
        const currentDate = new Date();
        const age = currentDate.getFullYear() - dobDate.getFullYear();
        if (age < 15 || age > 80) {
          errorMessages.textContent += "Age must be between 15 and 80.n";
          event.preventDefault();
        }
      }

      // State and Postcode Validation

      const stateToPostcode = {
        VIC: ["3", "8"],
        NSW: ["1", "2"],
        QLD: ["4", "9"],
        NT: ["0"],
        WA: ["6"],
        SA: ["5"],
        TAS: ["7"],
        ACT: ["0"],
      };
      if (!stateToPostcode[state] || !stateToPostcode[state].test(postcode)) {
        errorMessages.textContent +=
          "Postcode does not match selected state.n";
        event.preventDefault();
      }

      // Other Skills Text Area Validation
      if (otherSkillsCheckbox.checked && otherSkillsText.trim() === "") {
        errorMessages.textContent += "Please provide other skills.n";
        event.preventDefault();
      }
      return true;
    });
}

and this is the form in html

 <div class="form-container">
                <h1 id="title">Application Form</h1>
                <form id="registrationForm" onsubmit=" validateForm();">
                    <div class="mb-10">
                        <label class="form-label" for="JobRef">Job reference number</label>
                        <input type="text" name="JobRef" id="JobRef" required readonly>
                    </div>

                    <div class="mb-10">
                        <label class="form-label" for="First name">First name</label>
                        <input type="text" name="firstName" pattern="[A-Za-z]{1,20}" id="firstName" required>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="Last name">Last name</label>
                        <input type="text" name="lastName" pattern="[A-Za-z]{1,20}" id="lastName" required>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="dob">Date of birth</label>
                        <input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" required>
                    </div>

                    <!-- <span id="dobError" style="color: red;"></span> -->

                    <div class="mb-10">
                        <fieldset>
                            <legend>Gender:</legend>
                            <label>
                                <input type="radio" name="gender" value="male" required>
                                Male
                            </label>
                            <label>
                                <input type="radio" name="gender" value="female">
                                Female
                            </label>
                            <label>
                                <input type="radio" name="gender" value="other">
                                Other
                            </label>
                        </fieldset>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="Street Address">Street Address</label>
                        <input type="text" name="address" id="address" maxlength="40" required>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="Suburb/town">Suburb/town</label>
                        <input type="text" name="town" maxlength="40" id="town" required>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="state">State</label>
                        <select id="state" name="state" required>
                            <option value="">Select a State</option>
                            <option value="VIC">VIC</option>
                            <option value="NSW">NSW</option>
                            <option value="QLD">QLD</option>
                            <option value="NT">NT</option>
                            <option value="WA">WA</option>
                            <option value="SA">SA</option>
                            <option value="TAS">TAS</option>
                            <option value="ACT">ACT</option>
                        </select>

                    </div>
                    <!-- <span id="stateError" style="color: red;"></span> -->
                    <div class="mb-10">
                        <label class="form-label" for="postcode">Postcode</label>
                        <input type="text" name="postcode" id="postcode" pattern="[0-9]{4}" required>
                    </div>
                    <!-- <span id="postcodeError" style="color: red;"></span> -->

                    <div class="mb-10">
                        <label class="form-label" for="Email address">Email address</label>
                        <input type="email" name="email" id="email" required>
                    </div>
                    <div class="mb-10">
                        <label class="form-label" for="Phone number">Phone number</label>
                        <input type="text" name="phoneNumber" id="phoneNumber" pattern="[0-9s]{8,12}" required>
                    </div>
                    <div class="mb-10">
                        <fieldset>
                            <legend>Choose your skills</legend>
                            <input type="radio" name="skills" id="Html" value="HTML" required>
                            <label for="Html">HTML</label><br>
                            <input type="radio" id="css" name="skills" value="CSS">
                            <label for="css">CSS</label><br>
                            <input type="radio" id="javascript" name="skills" value="JavaScript">
                            <label for="javascript">JavaScript</label>
                        </fieldset>
                        <br>

                        <div class="mb-10">
                            <label class="form-check-label" for="skillsOther">Other Skills</label>
                            <input type="checkbox" name="skillsOtherCheckbox" id="skillsOtherCheckbox">
                            <textarea rows="10" cols="30" name="skillsOther" id="skillsOther" required> </textarea>
                        </div>
                        <!-- <span id="skillsOtherError" style="color: red;"></span> -->

                    </div>

                    <div id="errorMessages" style="color: red;"></div>

                    <div class="mb-10">
                        <button type="submit"> Submit</button>
                    </div>

                </form>
            </div>

2

Answers


  1. You are adding the event listeer on form submission. You have to just call the function instead. Remove the addEventListener:

    function validateForm() {
        const dobInput = document.getElementById('dob').value;
        const state = document.getElementById('state').value;
        const postcode = document.getElementById('postcode').value;
        const firstName = document.getElementById('firstName').value;
        const lastName = document.getElementById('lastName').value;
        const otherSkillsCheckbox = document.getElementById('otherSkills');
        const otherSkillsText = document.getElementById('otherSkillsText').value;
        const errorMessages = document.getElementById('errorMessages');
        errorMessages.textContent = ''; // Clear previous error messages
    
        // Date of Birth Validation
        const dobRegex = /^(d{2})/(d{2})/(d{4})$/;
        if (!dobRegex.test(dobInput)) {
            errorMessages.textContent += 'Invalid date format (dd/mm/yyyy).n';
            event.preventDefault(); // Prevent form submission
        } else {
            const [, day, month, year] = dobRegex.exec(dobInput);
            const dobDate = new Date(`${year}-${month}-${day}`);
            const currentDate = new Date();
            const age = currentDate.getFullYear() - dobDate.getFullYear();
            if (age < 15 || age > 80) {
                errorMessages.textContent += 'Age must be between 15 and 80.n';
                event.preventDefault();
            }
        }
    
        // State and Postcode Validation
    
        const stateToPostcode = {
            VIC: ['3', '8'],
            NSW: ['1', '2'],
            QLD: ['4', '9'],
            NT: ['0'],
            WA: ['6'],
            SA: ['5'],
            TAS: ['7'],
            ACT: ['0'],
        };
        if (!stateToPostcode[state] || !stateToPostcode[state].test(postcode)) {
            errorMessages.textContent += 'Postcode does not match selected state.n';
            event.preventDefault();
        }
    
        // Other Skills Text Area Validation
        if (otherSkillsCheckbox.checked && otherSkillsText.trim() === '') {
            errorMessages.textContent += 'Please provide other skills.n';
            event.preventDefault();
        }
        return true;
    }
    
    Login or Signup to reply.
  2. What @Xaver said AND …

    … is there a missing "event" parameter for the validateForm() Function to get the event.preventDefault() function running? validateForm(event)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search