hello,

I have 3 textboxes and user should fill atleast 1 of those.
so i have to check that.
How to do it using Required field validator/javascript function.

Note: I am not using form , the text boxes are in content holder of the page. If i use javascript how to call it on submit button which has insert code also.

Dani AI

Generated

A practical, robust approach is to use one ASP.NET CustomValidator that enforces "at least one filled" and implement both client-side (fast UX) and server-side (security) checks. RequiredFieldValidator is per-control, so using several of them (or creating them dynamically as suggested) works but is harder to maintain. A single CustomValidator centralizes the rule and keeps client+server logic consistent.

Key points and common pitfalls seen in this thread:

  • Client function must return a boolean and the button must use a return call so the browser can cancel postback. If you just call the function (no return) the server OnClick will still run — this explains why saw inserts despite validation.
  • Trim user input before testing ( and were right — spaces can fool a simple non-empty check). Use trim() (with a fallback) or test via a regex or server-side IsNullOrWhiteSpace.
  • When locating controls on the page be careful with ASP.NET client IDs inside master pages/content placeholders — use TextBox.ClientID (or ClientIDMode="Static" in newer ASP.NET) or select inputs with querySelectorAll('input[type="text"]')/jQuery rather than iterating childNodes (that returns text nodes and whitespace).

Always re-check on the server (CustomValidator.ServerValidate or Page.IsValid in the click handler) because client JS can be bypassed. Troubleshooting: check the browser console for JS errors, initialize your flag variables (avoid undefined), and test both with normal text and with only whitespace to confirm trimming works.

Example wiring (markup + server handler idea):

<asp:CustomValidator ID="cvAny" runat="server"
  ClientValidationFunction="validateAny"
  OnServerValidate="cvAny_ServerValidate"
  ErrorMessage="Enter at least one value" />

// Server-side
protected void cvAny_ServerValidate(object source, ServerValidateEventArgs e) {
  e.IsValid = !string.IsNullOrWhiteSpace(TextBox1.Text)
           || !string.IsNullOrWhiteSpace(TextBox2.Text)
           || !string.IsNullOrWhiteSpace(TextBox3.Text);
}

Recommended Answers

All 7 Replies

Create instances of RequiredField control dynamically.

Refere this sample code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage7.aspx.cs" Inherits="DemoPage7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Minimize IE</title>

    <script language="javascript">
        function validateTextBoxes() {

            //store trimmed values of textboxes into variables
            var txt1 = document.getElementById('TextBox1').value.replace(/^\s+|\s+$/g, '');
            var txt2 = document.getElementById('TextBox2').value.replace(/^\s+|\s+$/g, '');
            var txt3 = document.getElementById('TextBox3').value.replace(/^\s+|\s+$/g, '');

            if ((txt1 == null || txt1 == "") &&
                (txt2 == null || txt2 == "") &&
                (txt3 == null || txt3 == "")) {
                alert('Atlease one textbox should be entered');
                return false;
            }
            else
                return true;
        }
        
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="100%">
            <tr>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    &nbsp;<asp:Button ID="btnSubmit" OnClientClick="return validateTextBoxes()" runat="server"
                        Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

try using dreamweaver validate form function. then use the code from the onclick or onblur whatever event is there and move it to the respective textbox. the validate form feature uses javascript.

following is my javascript code :

<script>
function Check(frm) 
{
var input, notEmpty; 
var div = document.getElementById("chk");
for(var i=0;i<div.childNodes.length;i++) 
{
input = div.childNodes[i];
if(input.type == "text") 
{
if(input.value != "") 
{
notEmpty = true;break; 
}
else
{
notEmpty = false; 
}
}
}
if(notEmpty == false) 
{
alert("Atleast one email id must be entered."); 
}
return notEmpty; 
}
</script>

and I am checking for server side validations like email also on the same button click.

So tell me how to check both and how to call this script.

my friend this logic is not gonna work.....

if i add two spaces....that will blow your logic...

may be u should try the logic suggested by Mr. Ramesh..

Hope it helps...

following is my javascript code :

<script>
function Check(frm) 
{
var input, notEmpty; 
var div = document.getElementById("chk");
for(var i=0;i<div.childNodes.length;i++) 
{
input = div.childNodes[i];
if(input.type == "text") 
{
if(input.value != "") 
{
notEmpty = true;break; 
}
else
{
notEmpty = false; 
}
}
}
if(notEmpty == false) 
{
alert("Atleast one email id must be entered."); 
}
return notEmpty; 
}
</script>

and I am checking for server side validations like email also on the same button click.

So tell me how to check both and how to call this script.

The problem is that it is executing the onclick code and insert the data , whether the textboxes are filled or not.

I used Page.IsValid condition also

I think the code inside the for loop and if condition is not executed.

Set the value of the notEmpty to false by default.

var input, notEmpty = false;

Also call this function in the OnClientClick of the button as below

OnClientClick="return Check(form1)"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.