Hi everyone,

I have a web page where a fields needs to be validated if another is not empty. e.g. 'date' needs to be checked if 'quantity' has a number in it. I’m not exactly a pro with .net and am fiddling with compare and custom validators. All help on how/if this can be done much appreciated

Try this code.

.aspx code

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

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Quantity : &nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox><br />
        Date  : &nbsp;&nbsp;&nbsp; 
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>        
        <asp:CustomValidator ID="cvValidateDate" runat="server" ErrorMessage="Date must be entered"></asp:CustomValidator><br />
        <asp:Button ID="btnValidate" runat="server" Text="Validate" 
            onclick="btnValidate_Click" />
        
    </div>
    </form>
</body>
</html>

C# code

protected void btnValidate_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(txtQuantity.Text))
        {
            int qty = int.Parse(txtQuantity.Text);
            if (qty > 0)
            {
                if (String.IsNullOrEmpty(txtDate.Text))
                {
                    cvValidateDate.ErrorMessage = "Date must be entered";
                    cvValidateDate.IsValid = false;
                }
            }
        }
    }
commented: Thanks for your help. Thats exactly what I need +3

Thanks Ramesh S, this is great. Exactly what I was looking for.

Just in case anyone is interested , here is the same script in VB:

Protected Sub btnValidate_Click(ByVal sender As Object, ByVal e As EventArgs)
        If Not [String].IsNullOrEmpty(txtQuantity.Text) Then
            Dim qty As Integer = Integer.Parse(txtQuantity.Text)
            If qty > 0 Then
                If [String].IsNullOrEmpty(txtDate.Text) Then
                    cvValidateDate.ErrorMessage = "Date must be entered"
                    cvValidateDate.IsValid = False
                End If
            End If
        End If
    End Sub

asddsfasdfsdaf

ponka ponka
asdfas
asdfas
asdfsafas

Quoted Text Here
asdfasfdas

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.