Adding Validation to Web Parts

Posted by (JavaScript must be enabled to view this email address) on Wed 21 Jan 2009

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

Your Comments

Post a Comment

Name

Email Address

Website

Remember my personal information

Notify me of follow-up comments?

Please enter the word you see in the image below:


← Back to Blog Homepage

About our Blog

Brantas Limited specialise in Dynamics CRM, SharePoint and System Integration using the Microsoft Platform. We are all experienced developers in various fields with our own specialities complementing those of our team.

We have been working with SharePoint since 2003, including Installation and Administration, Migration, Development and Support.

Related Solutions

    No Related Posts Found

Related Case Studies

    No Related Posts Found