Client side validation for your user controls
Tue, 07/05/2011 - 12:07 — sylvainWhen building user controls in .NET, you sometimes want them validated, just like the default .NET controls. Of course, you could implement validation yourself, by hand, using JavaScript and some server code, which, funnily enough, sometimes is suggested on the interwebz...
The better option is to use the validator controls of .NET. Out of the box, those will not work on you controls, however.
Validation has 2 "modes", if you will. The first is client side validation, which enhances user experience by not posting back to the server. The second one is server side validation. This is where stuff is validated on the server at postback. Enabling server side validation is easy. You just decorate your user control with a ValidationProperty attribute. Like so:
[ValidationProperty("Text")]
public partial class RoleControl : System.Web.UI.UserControl, INamingContainer {
public string Text {
get {
return txtTextboxInMyUserControl.Text;
}
}
}In this case, the user control's Text property will be used for validation on postback. Unfortunately this doesn't help client side validation. Client side validation needs the client side id of the control involved. Validator controls however, only take id's of existing -in their own scope- controls. Which isn't of much use, since the actual control that needs validation is not in scope for the validator control. The problem is that the validator doesn't get the correct clientid for the control. Enter the overridden ClientID property.
public partial class RoleControl : System.Web.UI.UserControl, INamingContainer {
public string Text {
get {
return txtTextboxInMyUserControl.Text;
}
}
public override ClientID {
get {
return txtTextboxInMyUserControl.ClientID;
}
}
}Now you got a user control which will get validated both on the server and on the client...