Friday, July 30, 2010

How to: Validate User Control

How to validate user controls?

There is no quick way of validating user control. Following solutions might help.

Solution 1:
Usually, you can validate like following:
Page.Validate("MyValidationGroupOfDateUserControl");//Date user control
Page.Validate("MyValidationGroupOfAddressUserControl");//Address user control
if(Page.IsValid)
{
    //Do Something, Save/etc.
}
else
 ShowError("Some method to show error; "missing fields.");
But what if you want the validation to be client side?

One way could be to add a public property in your user control for validation group

public string ValidationGroup
{
       set
        {
            SetValidationGroup(value);
        }
}

//Sets the validations for all your controls
private void SetValidationGroup(string val)
{
        txtName.ValidationGroup = val;
        txtLocation.ValidationGroup = val;
 RequiredFieldValidator1.ValidationGroup = val;
 RequiredFieldValidator2.ValidationGroup = val;
}

And in your markup set it like:


Or if its in tab panel, that is, if you have your control displayed under a tab. Use following code:

<_asp:TabPanel runat="server" ID="pnlAddress" HeaderText="<%$ Resources:Resource, UserControls_Address %>">
                        
                            


Solution 2:

Add the validation group in the base class; and sub class your controls from it.

public class UserControlBase : UserControl
{
    public UserControlBase()
    {
        this.Load += new EventHandler(UserControlBase_Load);
    }

    void UserControlBase_Load(object sender, EventArgs e)
    {
        SetValidationGroup();
    }

    /// 
    /// Sets the validation group.
    /// 
    private void SetValidationGroup()
    {
        foreach (Control control in this.Controls)
        {
            //See if its ValidationGroup'able?
            if (control.GetType().GetProperty("ValidationGroup") == null) continue;

            //If you want to set validation for specific controls, 
            //for instance only for text boxes and drop down lists.
            //then, iterate through following.
            switch (control.GetType().ToString())
            {
                case "System.Web.UI.WebControls.DropDownList":
                case "System.Web.UI.WebControls.TextBox":
                    control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
                    break;
            }

            //Set for all controls; if you want.
            //control.GetType().GetProperty("ValidationGroup").SetValue(control, ValidationGroup, null);
        }
    }

    public string ValidationGroup
    {
        get { return (string)ViewState["ValidationGroup"]; }
        set { ViewState["ValidationGroup"] = value; }
    }

    /// 
    /// Clears the controls.
    /// 
    /// 


The parent.public void ClearControls(Control parent)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.Controls.Count > 0)
            {
                ClearControls(c);
            }
            else
            {
                switch (c.GetType().ToString())
                {
                    case "System.Web.UI.WebControls.TextBox":
                        ((TextBox)c).Text = "";
                        break;
                    case "System.Web.UI.WebControls.CheckBox":
                        ((CheckBox)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.RadioButton":
                        ((RadioButton)c).Checked = false;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        ((DropDownList)c).SelectedIndex = -1;
                        break;
                }
            }
        }
    }

}

In your control, write:

//Address user control
public partial class UCtlAddress : System.Web.UI.UserControl
{
...
}

Note couple of utility functions that you provide in your base user control; just so it may come handy at any time.

Use it similar to above in your markup;



Happy coding, and yep... I love GhostDoc! (0:

1 comment:

  1. Anonymous6:35 AM

    Mr. Khan
    I have been looking for this solution for Hrs.,

    Thanks

    ReplyDelete

Related Posts

Popular Posts