You are currently browsing the tag archive for the ‘VALIDATION’ tag.

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="">


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;
}
}
}
}

///
/// Quick changes the page if you have grid in your user control.
///

///

The grid.///

The data table.///

The event object instance containing the event data.public void ChangePage(GridView gvGrid, DataTable dt, GridViewPageEventArgs e)
{
gvGrid.PageIndex = e.NewPageIndex;
try
{
gvGrid.DataSource = dt;
gvGrid.DataBind();
}
catch { throw; }
}
}

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:

A lot of times I have come across this question on several forums; and to not avail the google, the question is being asked again and again. If at any point someone might feel they should google, and if google ever planned to re-rank my site to a higher level – then I’d guarantee that following code would work.

I did a reply to a post here on StackOverflow; though my code is pretty old – out of my project code – but as they say, old is gold, so here it goes.

Usage:

XMLValidator val = new XMLValidator();
if (!val.IsValidXml(File.ReadAllText(@"d:\Test2.xml"), @"D:\Test2.xsd"))
MessageBox.Show(val.Errors);

Code:

public class CXmlValidator
{
private int nErrors = 0;
private string strErrorMsg = string.Empty;
public string Errors { get { return strErrorMsg; } }
public void ValidationHandler(object sender, ValidationEventArgs args)
{
nErrors++;
strErrorMsg = strErrorMsg + args.Message + "\r\n";
}

public bool IsValidXml(string strXml/*xml in text*/, string strXsdLocation /*Xsd location*/)
{
bool bStatus = false;
try
{
// Declare local objects
XmlTextReader xtrReader = new XmlTextReader(strXsdLocation);
XmlSchemaCollection xcSchemaCollection = new XmlSchemaCollection();
xcSchemaCollection.Add(null/*add your namespace string*/, xtrReader);//Add multiple schemas if you want.

XmlValidatingReader vrValidator = new XmlValidatingReader(strXml, XmlNodeType.Document, null);
vrValidator.Schemas.Add(xcSchemaCollection);

// Add validation event handler
vrValidator.ValidationType = ValidationType.Schema;
vrValidator.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

//Actual validation, read conforming the schema.
while (vrValidator.Read()) ;

vrValidator.Close();//Cleanup

//Exception if error.
if (nErrors > 0) { throw new Exception(strErrorMsg); }
else { bStatus = true; }//Success
}
catch (Exception error) { bStatus = false; }

return bStatus;
}
}

Here is a kb that demonstrates the use of several types of validation. This site provides Xml/Schema validation online.

Following is the code using non deprecated methods.

public bool IsValidXmlEx(string strXmlLocation, string strXsdLocation)
{
bool bStatus = false;
try
{
// Declare local objects
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler);
rs.Schemas.Add(null, XmlReader.Create(strXsdLocation));

using (XmlReader xmlValidatingReader = XmlReader.Create(strXmlLocation, rs))
{ while (xmlValidatingReader.Read()) { } }

////Exception if error.
if (nErrors > 0) { throw new Exception(strErrorMsg); }
else { bStatus = true; }//Success
}
catch (Exception error) { bStatus = false; }

return bStatus;
}

void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: " + Environment.NewLine;
else strErrorMsg += "ERROR: " + Environment.NewLine;
nErrors++;
strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
}

Happy validation!

%d bloggers like this: