Home > Software design >  How do I get form validation to ignore a non required field?
How do I get form validation to ignore a non required field?

Time:01-10

I am trying to get my code to ignore a specific field that doesn't require text at all, but if it has anything other than numeric values in it, it will give me an error. Instead, it gives me the errors when Nothing is entered. The code I have in question is a regex function for checking numeric value, my validation function calls to the numeric regex function, and if input.classList.contains "numeric", if the regex is not validated, it will give an error. My entire code is posted below, as I don't know where the issue is

const checkAlphabet = (input) => {
    const required = /^([A-Za-z]) $/;
    const validate = required.test(input);
    return validate;
};

const checkAlphaNumeric = (input) => {
    const required = /^([A-Za-z0-9]) $/;
    const validate = required.test(input);
    return validate;
};

const checkAlphaNumericId = (input) => {
    const required = /^([A-Za-z0-9]) $/;
    const validate = required.test(input);
    return validate;
};

const checkWhiteSpace = (input) => {
    const required = /^([^-\s]) $/;
    const validate = required.test(input);
    return validate;
};

const checkNumeric = (input) => {
    const required = /^([0-9]) $/;
    const validate = required.test(input);
    return validate;
};

const checkDateReq = (input) => {
    const required = /^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d $/;
    const validate = required.test(input);
    return validate;
};

const checkPhoneNumber = (input) => {
    const required = /^\s*(?:\ ?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d ))?\s*$/;
    const validate = required.test(input);
    return validate;
};

const checkPassWord = (input) => {
    const required = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]). $/;
    const validate = required.test(input);
    return validate;
};

const checkLength = (input, minLength) => {
    input == minLength
};

const performValidation = (event) => {
    event.preventDefault();
    const form = event.target.form;
    const errorsDiv = form.previousElementSibling;
    const errorContainer = document.createElement('ul');
    if (errorsDiv.firstChild) {
        errorsDiv.removeChild(errorsDiv.lastChild);
    }
    errorsDiv.appendChild(errorContainer);
    for (const input of form) {
        const fieldInput = input.value;
        if (input.classList.contains("required")) {
            if (!checkWhiteSpace(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Required fields mut have a value that is not empty or whitespace."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("required_size")) {
            if (!checkLength(fieldInput.length, input.minLength)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Required_size field lengths must exactly match the minlength attribute of that field."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("alphabetic")) {
            if (!checkAlphabet(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Alphabetic fields must be a series of alphabetic characters"
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("username")) {
            if (!checkAlphaNumeric(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Alphanumeric fields must be a series of alphanumeric characters"
                errorContainer.appendChild(errorMesg);
            }
            if (fieldInput.length < 8) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Username fields must contain at least 8 characters."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("numeric")) {
            if (!checkNumeric(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Numeric fields must have a series of numeric characters."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("date")) {
            if (!checkDateReq(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Date fields must match the format of XX/XX/XXXX."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("phone")) {
            if (!checkPhoneNumber(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Phone fields must match the format of XXX-XXX-XXXX."
                errorContainer.appendChild(errorMesg);
            }
        }
        if (input.classList.contains("password")) {
            if (!checkPassWord(fieldInput)) {
                const errorMesg = document.createElement('li');
                errorMesg.className = 'errorMsgDis';
                errorMesg.innerHTML = "Password fields must contain one or more of the following types: uppercase letters, lowercase letters, numbers, special characters."
                errorContainer.appendChild(errorMesg);
            }
        }
    }
};

const validPress = () => {
    const buttons = document.getElementsByName("submitBtn");
    for (const button of buttons) {
        button.addEventListener("click", performValidation);
    }
}
validPress();

And HTML

<!DOCTYPE html>

<!-- Use this html file to verify your javascript library is functional you should not need to make
any changes to this file for your Javascript library to work -->


<html>

<head>
    <title>Form Validation Project</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <!-- Location of user Validation Javascript -->
    <script type="text/javascript" src="./index.js" defer></script>
    <!-- Optional user Validation stylesheet -->
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <br>
    <div >
        <div >
            <div >
                <h3 >Form One</h3>
            </div>
            <div >
                <div >
                    <!-- Error messages can go here -->
                </div>
                <form novalidate>
                    <div>
                        <label for="firstname">First Name : </label>
                        <input type="text" name="firstname" id="firstname"  /> Required Field
                    </div>
                    <div>
                        <label for="lastname">Last Name : </label>
                        <input type="text" name="lastname" id="lastname"  /> Required Field
                    </div>
                    <div>
                        <label for="username">Username : </label>
                        <input type="text" name="username" id="username" /> Required Field
                    </div>
                    <div>
                        <label for="password">Password : </label>
                        <input type="text" name="password" id="password" /> Required Field
                    </div>
                    <div>
                        <label for="zip">Zip Code : </label>
                        <input type="text" name="zip" id="zip"  minlength="5" /> Number, Minimum Length 5
                    </div>
                    <div>
                        <label for="ID">Employee ID : </label>
                        <input type="text" name="ID" id="ID"  /> Number, Required
                    </div>
                    <div>
                        <input type="submit" name="submitBtn" value="Validate">
                    </div>
                </form>
            </div>
        </div>
    </div>


    <div >
        <div >
            <div >
                <h3 >Form Two</h3>
            </div>
            <div >
                <div >
                    <!-- Error messages can go here -->
                </div>
                <form novalidate>
                    <div>
                        <label for="bananas">Quantity of bananas : </label>
                        <input type="text" name="bananas" id="bananas"  /> Number, not Required
                    </div>
                    <div>
                        <label for="weekday">Weekday : </label>
                        <input type="text" name="weekday" id="weekday"  /> Required Field
                    </div>
                    <div>
                        <label for="phone">Phone Number : </label>
                        <input type="text" name="phone" id="phone" /> phone
                    </div>
                    <div>
                        <label for="alphaID">Alphanumeric ID : </label>
                        <input type="text" name="alphaID" id="alphaID"  minlength="5" /> Minimum Length 5 Required
                    </div>
                    <div>
                        <label for="painLevel">Pain Level : </label>
                        <input type="text" name="painLevel" id="painLevel"  minlength="1" /> Number, Required Size 1
                    </div>
                    <div>
                        <label for="Date">Date : </label>
                        <input type="text" name="Date" id="date" /> Date
                    </div>
                    <div>
                        <input type="submit" name="submitBtn" value="Validate">
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

CodePudding user response:

Your regex /^([0-9]) $/ in checkNumeric() expects at least one number because of the . Try /^([0-9])*$/. This accepts empty string as well, because * matches 0 til infinity digits.

  •  Tags:  
  • Related