I have two textboxes on an asp.net webpage, either one or both are required to be filled in. Both cannot be left blank. How do I create a validator to do this in asp.net?
Try a CustomValidator.
You'll need to create a method that does the following to handle the ServerValidate event:
void ServerValidation (object source, ServerValidateEventArgs args)
{
args.IsValid = TextBox1.Text.Length > 0 || TextBox2.Text.Length > 0;
}
You'd need a CustomValidator to accomplish that.
Here is some code demonstrating basic usage. The custom validator text will show after IsValid is called in the submit callback and some text will be displayed from the Response.Write call.
ASPX
<asp:TextBox runat="server" ID="tb1" />
<asp:TextBox runat="server" ID="tb2" />
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
Display="Dynamic"
ErrorMessage="One of the text boxes must have valid input.">
</asp:CustomValidator>
<asp:Button runat="server" ID="uxSubmit" Text="Submit" />
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
uxSubmit.Click += new EventHandler(uxSubmit_Click);
}
void uxSubmit_Click(object sender, EventArgs e)
{
Response.Write("Page is " + (Page.IsValid ? "" : "NOT ") + "Valid");
}
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (tb1.Text.Length > 0 || tb2.Text.Length > 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With