Form Validator Check

Catch missing data. Instead of writing separate checks for every single field, this script iterates through the form collection to validate everything at once.

Copy the Script

<script>
function validateForm() {
    var inputs = document.getElementsByClassName("required");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].value == "") {
            alert("Please fill out all required fields.");
            inputs[i].focus();
            return false;
        }
    }
    return true;
}
</script>

<form onsubmit="return validateForm()">
    <input type="text" class="required">
    <input type="text" class="required">
    <button type="submit">Submit</button>
</form>

Frequently Asked Questions

It depends on the loop. The example script checks all `` elements. You should generally add logic to skip fields with `type='hidden'` or `disabled` status.

Yes. Inside the loop, if an empty value is found, you can set `field.style.border = '1px solid red'` to alert the user visually.

The HTML5 `required` attribute is better for modern browsers. This script is useful for custom logic, older browser support, or validating complex groups of inputs.