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

Recommended Answers

All 3 Replies

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">
    <form id="form1" runat="server">
        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" />

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


ponka ponka

Quoted Text Here

Be a part of the DaniWeb community

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