1

I have a form where the user needs to write their first name, last name, email address, and phone number. The user has to be based in the UK for this to work.

I have no problem preventing the form to be submitted if the inputs are blank or the format is not correct, however, I cannot submit the form successfully once all the input values are correct.

I know it has something to do with my stopSubmit code, but I can't seem to turn true into false once all the input values are correct.

Here is my Javascript code:

window.onload = function () {
let theForm = document.getElementById("form");
theForm.addEventListener("submit", function (event) {
    let stopSubmit = false;
    for (let i = 0; i < theForm.elements.length; i++) {
        cleanUpErrors();
        if (!checkFirstName(theForm.elements[0])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkLastName(theForm.elements[1])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkEmail(theForm.elements[2])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkPhone(theForm)) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
    }
    if (stopSubmit) {
        event.preventDefault();
    }
    }, false)
}

function checkFirstName(input) {
    let elemPos = document.getElementById("firstName");
    let inputValue = input.value;
    let errorMessage = "";
    if (inputValue === null || inputValue === "") {
        errorMessage = "This field is empty.";
    }
    if (inputValue !== "") {
        if (inputValue.length < 3) {
            errorMessage = "This field has less than 3 characters.";
        }
    }
    renderErrorMessage(elemPos, errorMessage);
}

function checkLastName(input) {
    let elemPos = document.getElementById("lastName");
    let inputValue = input.value;
    let errorMessage = "";
    if (inputValue === null || inputValue === "") {
        errorMessage = "This field is empty.";
    }
    if (inputValue !== "") {
        if (inputValue.length < 3) {
            errorMessage = "This field has less than 3 characters.";
        }
    }
    renderErrorMessage(elemPos, errorMessage);
}

function checkEmail(input) {
    let elemPos = document.getElementById("email");
    let emailValue = input.value;
    let errorMessage = "";
    let regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
    if (!emailValue.match(regex)) {
        errorMessage = "Not a valid email address.";
    }
    if (emailValue === "") {
        errorMessage = "This field is empty.";
    }
    renderErrorMessage(elemPos, errorMessage);
}

function checkPhone(input) {
    let elemPos = input.phone;
    let phoneValue = input.phone.value;
    let errorMessage = "";
    let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
    if (!phoneValue.match(regex)) {
        errorMessage = "Not a valid UK phone number.";
    }
    if (phoneValue === "") {
        errorMessage = "This field is empty.";
    }
    renderErrorMessage(elemPos, errorMessage);
}

function renderErrorMessage(selectedElem, errorMessage) {
    let errorElem = document.createElement("span");
    errorElem.setAttribute("class", "error");
    let errorText = document.createTextNode(errorMessage);
    errorElem.appendChild(errorText);
    selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
    return selectedElem;
}

function cleanUpErrors() {
    let indicator = document.getElementsByTagName("span");
    for (let i = 0; i < indicator.length; i++) {
        indicator[i].setAttribute("class", "hide");
    }
}

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Personal Information Form</title>
    <script src="scripts/test5.js"></script>
    <link rel="stylesheet" href="css/test.css">
</head>
<body>
<form id="form" action="test3success.html" novalidate="novalidate">
    <label for="firstName">First Name (required)</label>
    <input id="firstName" type="text" name="text" required>

    <label for="lastName">Last Name (required)</label>
    <input id="lastName" type="text" name="text" required>

    <label for="email">Email (required)</label>
    <input id="email" type="email" required>

    <label for="phone">Phone Number (required)</label>
    <input id="phone" type="tel" required>

    <button type="submit">Submit</button>
</form>
</body>
</html>
Jin Ri
  • 35
  • 3
  • `!checkFirstName(theForm.elements[0])` doesn't return true or false – Cjmarkham Mar 18 '20 at 19:45
  • None of them return anything. Also the test for the phone number is wrong (`!checkPhone(theForm)`). And why the loop? – Andreas Mar 18 '20 at 19:49
  • Take a look here: [Continue after preventdefault](https://stackoverflow.com/questions/7610871/how-to-trigger-an-event-after-using-event-preventdefault) – Renato Coqueiro Mar 18 '20 at 19:57

1 Answers1

0

Your checks need to return true or false considering you are evaluating these within if statements.

So, when you are doing

if (!checkFirstName(theForm.elements[0])) {

This evaluates to

if (!undefined) {

Since checkFirstName (and the others) return nothing (undefined), which means stopSubmit is always set to true

Note: There are cleaner ways to do this, I just did a check for errorMessage being blank.

Also as pointed out in the comments, you are passing the entire form to the checkPhone function, when you could just pass the input as you are doing with the other checks.

window.onload = function () {
  let theForm = document.getElementById("form");
  theForm.addEventListener("submit", function (event) {
    let stopSubmit = false;
    for (let i = 0; i < theForm.elements.length; i++) {
        cleanUpErrors();
        if (!checkFirstName(theForm.elements[0])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkLastName(theForm.elements[1])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkEmail(theForm.elements[2])) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
        if (!checkPhone(theForm)) {
            theForm.elements[i].style.borderColor = "#990000";
            stopSubmit = true;
        }
    }
    if (stopSubmit) {
        event.preventDefault();
        console.log('default prevented')
    }
    }, false)
}

function checkFirstName(input) {
    let elemPos = document.getElementById("firstName");
    let inputValue = input.value;
    let errorMessage = "";
    if (inputValue === null || inputValue === "") {
        errorMessage = "This field is empty.";
    }
    if (inputValue !== "") {
        if (inputValue.length < 3) {
            errorMessage = "This field has less than 3 characters.";
        }
    }
    renderErrorMessage(elemPos, errorMessage);
    if (errorMessage !== "") {
       return false
    }
    
    return true
    
}

function checkLastName(input) {
    let elemPos = document.getElementById("lastName");
    let inputValue = input.value;
    let errorMessage = "";
    if (inputValue === null || inputValue === "") {
        errorMessage = "This field is empty.";
    }
    if (inputValue !== "") {
        if (inputValue.length < 3) {
            errorMessage = "This field has less than 3 characters.";
        }
    }
    renderErrorMessage(elemPos, errorMessage);
    if (errorMessage !== "") {
       return false
    }
    
    return true
}

function checkEmail(input) {
    let elemPos = document.getElementById("email");
    let emailValue = input.value;
    let errorMessage = "";
    let regex = /^(([^<>()\[\]\\.,;:\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,}))$/;
    if (!emailValue.match(regex)) {
        errorMessage = "Not a valid email address.";
    }
    if (emailValue === "") {
        errorMessage = "This field is empty.";
    }
    renderErrorMessage(elemPos, errorMessage);
    if (errorMessage !== "") {
       return false
    }
    
    return true
}

function checkPhone(input) {
    let elemPos = input.phone;
    let phoneValue = input.phone.value;
    let errorMessage = "";
    let regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/;
    if (!phoneValue.match(regex)) {
        errorMessage = "Not a valid UK phone number.";
    }
    if (phoneValue === "") {
        errorMessage = "This field is empty.";
    }
    renderErrorMessage(elemPos, errorMessage);
    
    if (errorMessage !== "") {
       return false
    }
    
    return true
}

function renderErrorMessage(selectedElem, errorMessage) {
    let errorElem = document.createElement("span");
    errorElem.setAttribute("class", "error");
    let errorText = document.createTextNode(errorMessage);
    errorElem.appendChild(errorText);
    selectedElem.parentNode.insertBefore(errorElem, selectedElem.nextSibling);
    return selectedElem;
}

function cleanUpErrors() {
    let indicator = document.getElementsByTagName("span");
    for (let i = 0; i < indicator.length; i++) {
        indicator[i].setAttribute("class", "hide");
    }
}
label, .error, button {
  display: block;
}
<form id="form" action="test3success.html" novalidate="novalidate">
    <label for="firstName">First Name (required)</label>
    <input id="firstName" type="text" name="text" required>

    <label for="lastName">Last Name (required)</label>
    <input id="lastName" type="text" name="text" required>

    <label for="email">Email (required)</label>
    <input id="email" type="email" required>

    <label for="phone">Phone Number (required)</label>
    <input id="phone" type="tel" required>

    <button type="submit">Submit</button>
</form>
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • Thank you for this. I've removed the for loop and corrected the `checkPhone` code. It's working, but I'll obviously try to make it more elegant. Again, thank you. – Jin Ri Mar 18 '20 at 20:52