Friday, August 24, 2007

ControlToValidate can work with Custom Controls

Today I was trying to build a composite user control that is a basic text box with validators built in. All I wanted was a TextBox that could know what to set for a RegularExpressionValidator and a RequiredFieldValidator.

When I went to add a CompareValidator I ran into a problem... I couldn't specify my composite control as the ControlToCompare or the ControlToValidate. I got this error: "ControlToValidate property of CustomCalidator is Incorrect." So I went lookin' on Google and came up with a bunch of results that didn't actually help.

MSDN suggests you use the ValidationPropertyAttribute, but I couldn't get it to work. Yuri's post on the bottom of this page was REALLY close to being correct for asp.net 2.0 in that he used cbStates:Text. It's been quite a long time since I've used asp.net 1.1, and maybe ids were delimited with colons back then. But now, it's the $ sign. I didn't think to try it, but Brian gave it a whirl and it worked.

He explained to me that the page the CompareValidator sits on only knows of its child controls. So if you look at the unique id of the textbox you want to validate, it starts way higher: ctl100$BodyContent$Email$TextBoxField. The page can't figure out the relative "path", so you need to strip off ctl100$BodyContent$...$...$... I guess it's because the page doesn't implement INamingContainer.

Click to view code

Dont' be worried about the id not being recognized correctly. Because we always have TextBoxField inside the composite control, Password$TextBoxControl will always be valid.

Hope this helps!

2 comments:

Sven said...

Now it would be very funny to know how to do this at runtime.... I'm getting into serious trouble for several hours now.

jesse said...

Sorry, I forgot I changed some links around. The code link above should be updated. Hope that helps.