Custom Field Validation With SPFieldValidationException

There was a post in the newsgroups wondering how when constructing a custom field type how one might build a small generic validation function in order to verify the harvested user input. There is provided the SPField.GetValidatedString method, which is overridable, that can be used in order to achieve this since it will take the object input provided by the custom field type and provide a workable string representation.

An example of this method is this:

[csharp]

private readonly string m_strValidationException = “Hmmm, your string length wasen’t 10!”;

public override string GetValidatedString(object oValue)
{
if (oValue.ToString().Length != 10)

{
throw new SPFieldValidationException(m_strValidationException);
}

else

{
return oValue.ToString();
}

}

[/csharp]

Share

3 thoughts on “Custom Field Validation With SPFieldValidationException”

  1. This raises an exception and shows an error to the user instead of showing a friendly red label that the field wasn’t entered in to correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *