Export (0) Print
Expand All

Custom Field Data Validation

Last modified: March 13, 2010

Applies to: SharePoint Foundation 2010

Your custom field class can contain data validation. Each custom field type can inherit validation from its parent field class, can override its parent's validation, or even call its parent's validation as part of its own validation logic. You specify custom data validation and preupdate processing logic for your custom field class in an override of the GetValidatedString method. (The default implementation simply calls the ToString method of the value class; for this reason, if your field class inherits directly from SPField, or from a derived class that does not itself override the GetValidatedString method, you must override GetValidatedString to provide validation logic if any is needed.)

While you can perform data validation in several places in your code, including form controls, we strongly recommend that you add any server-side data validation logic needed to the GetValidatedString method of your custom field class. This helps ensure that the necessary data validation is applied both to the data in your field and to the data in the content database.

In cases where data is being updated through any of the following means:

  • by using a form control

  • through the user interface, or

  • programmatically through the object model,

SharePoint Foundation invokes the GetValidatedString method whenever data is stored in an SPField or derived class. For example, SharePoint Foundation invokes the GetValidatedString method when a field value in an SPListItem object is set using the SPListItem.this["field name"] method.

Note Note

It is possible for users to update the data in a field in ways that do not invoke the GetValidatedString method and therefore, do not invoke any data validation logic contained in the method. This includes using unmanaged code or Web service methods that do not invoke the SPListItem object to update the field data. For example, when a user updates list item data by using the datasheet view, the list items are updated without invoking the GetValidatedString method.

In addition, you can use the GetValidatedString method to return string error messages to the calling application or form, enabling you to provide graceful display and handling of data validation errors for your field class.

To return an error message, the GetValidatedString method should throw an SPFieldValidationException as an error. You can provide the appropriate error message as string parameters to the SPFieldValidationException constructor. In SharePoint Foundation, if the user enters an invalid value and clicks OK on the form, the message appears in red text next to the field on the standard New and Edit (list item) forms.

The following example shows an overridden version of GetValidatedString that verifies that the field has a value when it is a required field and that the string version of the value does not exceed a specified limit. (The Required property records whether the field is required or not.)

public override String GetValidatedString(Object value)
{
    if ((this.Required == true) && (value.ToString() == ""))
    {
        throw new SPFieldValidationException(this.Title 
            + " must have a value.");
    }
    else if (value.ToString().Length > MAXLENGTH)
    {
        throw new SPFieldValidationException(this.Title 
            + " cannot be longer than " + MAXLENGTH.ToString());
    }
    return base.GetValidatedString(value);
} 

If users may be setting the field's value in a UI other than the standard New or Edit (list item) forms, then you should also validate data that users enter into the field's UI control. In particular we recommend that if the field is required to have a value, this requirement should be enforced at the UI level. If you are using one of the built-in SharePoint Foundation classes that derive from BaseFieldControl to render your field, then you can rely on its internal validation to enforce Required. If you are deriving your own control from BaseFieldControl or one of its derivations and you override the Validate or CreateChildControls method, then you will need to provide the enforcement of Required as well as any other UI-level validation you want to do.

Your UI validation logic can be in either the Validate method or the CreateChildControls method or a combination of the two. One weakness of putting validation logic into the CreateChildControls method is that the method is only invoked when the field is being rendered on a form, so the validation does not occur if you update the value in the object model.

An override of the Validate method should report its outcome by setting the IsValid property to true or false and, in the latter case, setting ErrorMessage to an appropriate message.

The following is an example of an override of the Validate method. It first checks to see if the current control mode is Display, in which case it does not matter if the field is invalid because it cannot be changed anyway. The method also looks to see if the Value property is already known to be invalid by checking the IsValid property. If either of those checks is true, it does nothing. If neither is true, the method calls the base Validate which will set IsValid to false if it finds anything wrong with the Value property and set an appropriate ErrorMessage. (The BaseFieldControl.Validate method does nothing, so if the class whose Validate method is being overridden is derived directly from BaseFieldControl, then the call to the base Validate method can be omitted.) Finally, the method checks the value of Required and enforces that value.

public override void Validate()
{
    if (ControlMode == SPControlMode.Display || !IsValid)
    {
        return;
    }

    base.Validate();

    if (Field.Required && 
        (Value == null || Value.ToString().Length == 0))
    {
        this.ErrorMessage = Field.Title + " must have a value."
        IsValid = false;
        return;
    }
}
NoteNote

Use the RenderValidationMessage method to render the ErrorMessage.

Show:
© 2014 Microsoft