Search code examples
c#asp.netrequiredfieldvalidator

Error in RequiredFieldValidator control


.aspx file:

Postal Code:

<asp:TextBox runat="server" ID="txtPostalCode" CssClass="inputs" /><br />
 <asp:RegularExpressionValidator ID="regPostalCode" runat="server" ErrorMessage="Should be 5 Digits" ControlToValidate="txtPostalCode" ValidationExpression="\d{5}"></asp:RegularExpressionValidator>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtPostalCode" 
   Display="Dynamic" EnableClientScript="False" onload="RequiredFieldValidator1_Load"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Cannot be left blank" 
    Display="Dynamic" ControlToValidate="txtPostalCode" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

.aspx.cs file :

 protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{

    if (IsPostBack)
    {
        //get which input TextBox will be validated.
        TextBox tx = (TextBox)this.FindControl(
            RequiredFieldValidator1.ControlToValidate);
        if (string.IsNullOrEmpty(tx.Text))
        {
            RequiredFieldValidator1.ErrorMessage =
                "Required field cannot be left blank.";
        }
    }


}
protected void CustomValidator1_ServerValidate(object source,ServerValidateEventArgs args)
{
    //Test whether the length of the value is more than 6 characters
    if (args.Value.Length <= 5)
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

It shows me an error on the line : if (string.IsNullOrEmpty(tx.Text)) Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Iam not sure what to do can someone help me with this i will be very grateful.


Solution

  • The problem most likely is due to to the FindControl method not finding the textbox. If you are using a Master page, you should try using a recursive FindControl method like the one below. For the Root parameter, you can pass this.Master, and Id would be your RequiredFieldValidator1.ControlToValidate.

        TextBox tx = (TextBox)FindControlRecursive(this.Master, RequiredFieldValidator1.ControlToValidate);
    

    Recusive FindControl:

        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
                return Root;
    
            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            }
    
            return null;
        }