Adding Validation to Web Parts

Chances are if you have developed a web part in the past, it needed some user input. And if it needed user input then it needs validation.

When you develop webparts you are unable to do use the designer (thanks Microsoft) so you have to be a real coder and declare, instantiate and add the controls entirely programmatically. Including your validation controls. Ok, you've done that. Why doesn't your validation work?

First, you MUST (and I cant stress that enough) instantiate the validators in your overridden OnInit method, not in the CreateChildControls() method. Secondly, set up a validation group so that you can control what the validators are validating (you dont want to validate the whole page) and lastly, you need to ensure that the EnableClientScript property is enabled.



regexpval.ControlToValidate = this.txtEmail.ID;
regexpval.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
regexpval.ErrorMessage = "Please Enter a valid email address.";
regexpval.Display = ValidatorDisplay.Dynamic;
regexpval.EnableClientScript = true;
regexpval.ValidationGroup = validationGroup;


If you've been diligent then your code will compile, deploy and even let you place it on the page, but for some weird reason it still doesn't work as you think it should. AAAAARGH!

Its a small and very simple fix, the text box you are validating might be instantiated but it doesn't have an ID, D'oh!

All it takes is adding a line like this BEFORE you set up the validators:



txtEmail.ID = "txtEmail";


Happy Validating!

No comments:

Note: only a member of this blog may post a comment.

Powered by Blogger.