Universal Form Validator

One script to rule them all. Instead of writing custom checks for every form, use this generic validator loop to handle required fields automatically.

Copy the Script

<script>
function validateAll() {
    var valid = true;
    var errors = [];
    
    // Check Inputs
    var inputs = document.querySelectorAll(".required");
    inputs.forEach(function(input) {
        if (input.value.trim() === "") {
            valid = false;
            input.style.border = "1px solid red";
            errors.push("Missing text fields");
        } else {
            input.style.border = "";
        }
    });

    // Check Checkboxes
    var checks = document.querySelectorAll(".required-check");
    checks.forEach(function(box) {
        if (!box.checked) {
            valid = false;
            errors.push("Please check required boxes");
        }
    });

    if(!valid) alert("Errors: " + errors.join(", "));
    return valid;
}
</script>

<form onsubmit="return validateAll()">
    <input class="required">
    <input type="checkbox" class="required-check">
    <button>Send</button>
</form>

Frequently Asked Questions

Add a specific class (like `validate`) to the input elements. The script finds all elements with that class and checks their value.

Yes. You can add a `data-pattern` attribute to inputs and have the script check the value against that Regex.

Yes. If `validate()` returns true, you can proceed to call your Ajax submission function instead of the default form submit.