Validate At-least one TextBox from Multiple TextBoxes using JavaScript

I’ll demonstrate how to validate at least one TextBox from many TextBoxes in JavaScript using an example in this article.

HTML MarkUp:

Multiple HTML TextBoxes, an HTML SPAN element, and a Button make up the HTML Markup.
the Button to which an OnClick event handler has been assigned.

<table>
    <tr>
        <th colspan="2">Address Proofs (At-least one)</th>
    </tr>
    <tr>
        <td>Passport Number</td>
        <td>
            <input id="txtPassport" type="text" />
        </td>
    </tr>
    <tr>
        <td>Aadhar Number</td>
        <td>
            <input id="txtAadhar" type="text" />
        </td>
    </tr>
    <tr>
        <td>PAN Number</td>
        <td>
            <input id="txtPAN" type="text" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <span id="lblMessage" style="color: Red; visibility: hidden;">
                Please enter at-least one Address proof.
            </span>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <input type="button" value="Submit" onclick="ValidateAddressProof()" />
        </td>
    </tr>
</table>

Implementing validation using JavaScript:

The TextBoxes are first referenced inside the ValidateAddressProof JavaScript function, where the data are then retrieved and stored in the appropriate variables.
Then, a check is made for each value of the passport, Aadhar, and PAN numbers, respectively, one by one. The validation succeeds if at least one of them is valid; else, it fails.
Depending on whether the validation succeeded or failed, the isValid variable is set to True or False.
The outcome is then shown in the HTML SPAN element based on the isValid variable.

<script type="text/javascript">
    function ValidateAddressProof() {
        //Referencing and fetching the TextBox values.
        var passport = document.getElementById("txtPassport").value;
        var aadhar = document.getElementById("txtAadhar").value;
        var pan = document.getElementById("txtPAN").value;
 
        var isValid = false;
        //Check if Passport Number is not blank.
        if (passport.trim() != "") {
            isValid = true;
        }
 
        //Check if Aadhar Number is not blank.
        if (aadhar.trim() != "") {
            isValid = true;
        }
 
        //Check if PAN Number is not blank.
        if (pan.trim() != "") {
            isValid = true;
        }
 
        //Show or hide HTML SPAN based on IsValid variable.
        document.getElementById("lblMessage").style.visibility = !isValid ? "visible" : "hidden";
    }
</script>

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories