views:

2089

answers:

5

I am writing a webpart for MOSS 2007. I need to validate a text field in that webpart, or which I am using th required field validator.

I am creating the required field validator as follows:

vldProjectError = new RequiredFieldValidator();
vldProjectError.ForeColor = Color.Red;
vldProjectError.ErrorMessage = Resources.LABEL_PROJECT_ERROR;
vldProjectError.ControlToValidate = txtProjectName.ClientID;
vldProjectError.Display = ValidatorDisplay.Dynamic;
this.Controls.Add(vldProjectError);

The above code snippet is in th CreateChildControls() override. When i open this webpart page, i get a generic error message in SharePoint. I cannot trap the error by debugging.

I noticed that the exception is thrown after CreateChildControls() and before the Render() method, because the debugger never enters the Render() method

Any Idea how to use validators in sharepoint webparts? Is there anything I am missing?

A: 

Did you try enabling error output to the browser in the web.config? Maybe that will give you a more detailed message.

strongopinions
+2  A: 

I would try two things:

  1. Enabling error output is definitely helpful while developing for SharePoint, follow this post to enable it.
  2. Try assigning ControlToValidate property in the Render method, instead of in CreateChildControls. Or at least do it after txtProjectName is added to the control collection.
dstetsenko
A: 

I've had the same problem as you with validator controls. The controlId property of the validated control is null until you added it to the controls collection of the webpart. So, the validator has to be configured after this line:

this.Controls.Add(txtProjectName);

Check this debugging your webpart and look at the ClientId property of the validated control.

jaloplo
+2  A: 

I was able to solve the problem.

we should use

txtProjectName.ID = "txtProjectName";    
vldProjectError.ControlToValidate = txtProjectName.ID;

instead of

vldProjectError.ControlToValidate = txtProjectName.ClientID;

and this should be done inside CreateChidControls() method.

ashwnacharya
A: 

Thanks a lot ashwnan.

Your reply really helped me a lot.

Thanks, Srini