0

What I'm trying to do is make it so if a text field does not contain the "required" class and the field is empty, no error message will show up when the form is validated. The problem I have right now is that the password error message still shows up for the field without the "required" class. I've tried adding an if statement to the validate field function to check if the field doesn't contain the "required" class, but that doesn't appear to be working. Help much appreciated.

Functions:

const validateForm = (e) => {
    e = e.target;
    let messages = [];
    validateRequired(e, messages);
    validatePassword(e, messages);
    if (messages.length > 0) {
        let ul = document.createElement("ul");
        for (const message of messages) {
            let li = document.createElement("li")
            li.textContent = message;
            ul.appendChild(li);
        }
        e.parentElement.getElementsByClassName("errors")[0].innerHTML = "";
        e.parentElement.getElementsByClassName("errors")[0].appendChild(ul);
        return false;
    }
    return true;
}

const validateRequired = (e, messages) => {
    let fields = e.getElementsByClassName("required");
    for (const field of fields) {
        let input = field.value;
        if (input.trim().length === 0) {
            messages.push("Error.");
            break;
        }
    }
}

const validatePassword = (e, messages) => {
    let fields = e.getElementsByClassName("password");
    for (const field of fields) {
        let input = field.value;
        let allCharacters = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]*$/;
        if (!input.match(allCharacters)) {
            messages.push("Error.");
            break;
        }
    }
}

Form:

    <div>
        <label for="password">Password : </label>
        <input type="text" name="password" id="password" class="password" />
    </div>
    <div>
        <label for="requiredPassword">Required and Password : </label>
        <input type="text" name="requiredPassword" id="requiredPassword" class="required password" />
  • Do you want the 'validatePassword' function to only work when there is a 'required' class? Just replace 'let fields = e.getElementsByClassName("password"); ' with 'let fields = e.getElementsByClassName("required"); '. – JS KIM Mar 03 '21 at 02:59
  • No, "validatePassword" should work independently as long as there's a "password" class. – Laxidaze Mar 03 '21 at 03:04
  • If so, I think you can use 'classList'. For example, if (field.classList.contains('required')) {...} – JS KIM Mar 03 '21 at 03:27
  • Never mind, I found an alternative without changing the logic, I solved it by changing the regEx: https://stackoverflow.com/questions/5063977/regex-empty-string-or-email – Laxidaze Mar 03 '21 at 12:59

0 Answers0