Search code examples
asp.netsharepointmosssharepoint-2007web-parts

Adding a required field validator to a SharePoint webpart


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?


Solution

  • 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.