Return to Snippet

Revision: 49921
at August 2, 2011 09:01 by nickaranz


Initial Code
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<spuc:InputFormRequiredFieldValidator ID="UserNameValidator" runat="server" Display="Dynamic" SetFocusOnError="true"                                                                               ControlToValidate="TextBoxFromEmail" BreakBefore="true" ErrorMessage="Email is required" />

<spuc:InputFormRangeValidator ID="AgeValidator" runat="server" Display="Dynamic" SetFocusOnError="true"
      ControlToValidate="AgeInputFormTextBox" BreakBefore="true"
      Type="Integer" MinimumValue="21" MaximumValue="30"
      ErrorMessage="You must be between 21 and 30 years old." />

<spuc:InputFormRegularExpressionValidator ID="Validator" runat="server" Display="Dynamic" SetFocusOnError="true"
      ControlToValidate="EmailTextBox"
      ValidationExpression="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"
      ErrorMessage="Enter a valid email address." />

<spuc:InputFormCustomValidator ID="UsernameCustomValidator" runat="server" Display="Dynamic" SetFocusOnError="true"
      ControlToValidate="UsernameTextBox"
      OnServerValidate="ValidateUserName"
      ErrorMessage="Your user name must be at least 10 characters long (server-side validation)."
      ValidateEmptyText="true" />

In your code-behind you define the controls as protected class-level variables:

protected InputFormTextBox UsernameTextBox;
protected InputFormCustomValidator UsernameCustomValidator;
And you add the server-side validation method. This method accepts 2 incoming arguments:  a source object being the control to validate, and a args object having properties as Value and IsValid. The Value property contains the value to validate. Set the IsValid property to true if the validation is successful or set the IsValid property to false if the validation fails.

protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
    if (args.Value.Length >= 10)
        args.IsValid = true;
    else
        args.IsValid = false;
}

Initial URL
http://karinebosch.wordpress.com/sharepoint-controls/sharepoint-validation-controls/

Initial Description

                                

Initial Title
SharePoint Field Validator

Initial Tags
validation, Development, sharepoint

Initial Language
ASP