SharePoint Validation Controls
The Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll contains a number of validation controls that can be used on application pages and web parts to validate user entry in the SharePoint controls.
The different validation controls are:
- InputFormRequiredFieldValidator
- InputFormRangeValidator
- InputFormCompareValidator
- InputFormRegularExpressionValidator
- InputFormCheckBoxListValidator
- InputFormCustomValidator
If you want to use these SharePoint control validators, you have to add a page directive to the page:
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
The following sections describe the use of the different SharePoint validation controls.
The InputFormRequiredFieldValidator control
This control inherits from the standard ASP.NET RequiredFieldValidator and has the same functionality.
<spuc:InputFormTextBox ID="CompanyNameTextBox" runat="server" class="ms-input" Title="Company name" TextMode="SingleLine" Columns="40" /> <spuc:InputFormRequiredFieldValidator ID="UserNameValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="CompanyNameTextBox" BreakBefore="true" ErrorMessage="The company name is required" />
Properties inherited from the standard ASP.NET RequiredFieldValidator control:
- ControlToValidate: This property is required and must contain the id of the control to which this validator control applies.
- ErrorMessage: This property contains the error message that will be displayed when the validation fails.
- SetFocusOnError: When this property is set to true, the focus is set on the control that caused the validation to fail.
- EnableClientScript: Setting this property to false will bypass client-side validation.
Important properties of the SharePoint InputFormRequiredFieldValidator control:
- Display: This property influences the postion of the subsequent controls. If set to Static, the necessary space for the error message will be foreseen. Possible values are None, Dynamic and Satic.
- ErrorImageUrl: If this property is filled out, the image will be displayed together with the error message in case a validation error occurs.
- BreakAfter: When this property is set to true, a linke break is inserted after the error message.
- BreakBefore: When this property is set to true, a line break is inserted before the error message.
The InputFormRangeValidator control
This control inherits from the standard ASP.NET RangeValidator control and has the same functionality.
<spuc:InputFormTextBox ID="AgeInputFormTextBox" runat="server" class="ms-input" Title="Age" TextMode="SingleLine" Columns="3" /> <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." />
Properties inherited from the standard ASP.NET RangeValidator control:
- ControlToValidate: This property is required and must contain the id of the control to which this validator control applies.
- Type: indicates the type of data to validate. If this property is omitted, the default is String.
- MinimumValue: the lower boundary. The minimum value itself is considered as a valid entry.
- MaximumValue: the upper boundary. The maximum value itself is considered as a valid entry.
- ErrorMessage: This property contains the error message that will be displayed when the validation fails.
- SetFocusOnError: When this property is set to true, the focus is set on the control that caused the validation to fail.
- EnableClientScript: Setting this property to false will bypass client-side validation.
Important properties of the SharePoint InputFormRangeValidator control:
- Display: This property influences the postion of the subsequent controls. If set to Static, the necessary space for the error message will be foreseen. Possible values are None, Dynamic and Satic.
- ErrorImageUrl: If this property is filled out, the image will be displayed together with the error message in case a validation error occurs.
- BreakAfter: When this property is set to true, a linke break is inserted after the error message.
- BreakBefore: When this property is set to true, a line break is inserted before the error message.
The InputFormCompareValidator control
This control inherits from the standard ASP.NET CompareValidator control and has the same functionality.
<spuc:InputFormTextBox ID="MinimumTextBox" runat="server" class="ms-input" Title="Minimum value" TextMode="SingleLine" Columns="10" /> <br /> <spuc:InputFormTextBox ID="MaximumTextBox" runat="server" class="ms-input" Title="Maximum value" TextMode="SingleLine" Columns="10" /> <spuc:InputFormCompareValidator ID="InputFormCompareValidator1" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="MinimumTextBox" ControlToCompare="MaximumTextBox" Operator="LessThan" BreakBefore="true" Type="Integer" ErrorMessage="The first value must be lower than the second value." ErrorImageUrl="info.gif" />
Properties inherited from the standard ASP.NET CompareValidator control:
- ControlToValidate: This property is required and must contain the id of the control to which this validator control applies.
- ControlToCompare: This property is required and must contain the id of the control against which the first control must be validated.
- Type: indicates the type of data to validate. If this property is omitted, the default is String.
- Operator: This property specifies the comparison operation. Possible values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, DataTypeCheck.
- ErrorMessage: This property contains the error message that will be displayed when the validation fails.
- SetFocusOnError: When this property is set to true, the focus is set on the control that caused the validation to fail.
- EnableClientScript: Setting this property to false will bypass client-side validation.
Important properties of the SharePoint InputFormCompareValidator control:
- Display: This property influences the postion of the subsequent controls. If set to Static, the necessary space for the error message will be foreseen. Possible values are None, Dynamic and Satic.
- ErrorImageUrl: If this property is filled out, the image will be displayed together with the error message in case a validation error occurs.
- BreakAfter: When this property is set to true, a linke break is inserted after the error message.
- BreakBefore: When this property is set to true, a line break is inserted before the error message.
It is slightly different if you want to validate a date entered in a SharePoint DateTimeControl. This control is a composite control and you have to validate the date entered in the Date control:
<spuc:DateTimeControl ID="StartDateControl" runat="server" DateOnly="true" /> <spuc:InputFormCompareValidator ID="InputFormCompareValidator2" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="StartDateControl$StartDateControlDate" Type="Date" Operator="DataTypeCheck" BreakBefore="true" ErrorMessage="Please enter a valid date." ErrorImageUrl="info.gif" />
I got the milk from Greg Galipeau’s blog in his post about validating an DateTimeControl with a standard ASP.NET Compare validator.
The InputFormRegularExpressionValidator control
This validator control can be used to validate user input against a regular expression. It inherits from the standard ASP.NET RegularExpressionValidator. Following example checks wether the user entered a valid email address.
<spuc:InputFormTextBox ID="EmailTextBox" runat="server" class="ms-input" Title="Email" TextMode="SingleLine" Columns="60" /> <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." />
Properties inherited from the ASP.NET RegularExpressionValidator control:
- ControlToValidate: This property is required and must contain the id of the control to which this validator control applies.
- ValidationExpression: contains the regular expression against which the user entry must be validated.
- ErrorMessage: This property contains the error message that will be displayed when the validation fails.
- SetFocusOnError: When this property is set to true, the focus is set on the control that caused the validation to fail.
- EnableClientScript: Setting this property to false will bypass client-side validation.
Important properties of the SharePoint InputFormRegularExpressionValidator control:
- Display: This property influences the postion of the subsequent controls. If set to Static, the necessary space for the error message will be foreseen. Possible values are None, Dynamic and Satic.
- ErrorImageUrl: If this property is filled out, the image will be displayed together with the error message in case a validation error occurs.
- BreakAfter: When this property is set to true, a linke break is inserted after the error message.
- BreakBefore: When this property is set to true, a line break is inserted before the error message.
The InputFormCheckBoxListValidator control
This validator control can only be used against an InputFormCheckBoxList control (and not against an InputFormCheckBox control). It works as a required field validator: if no options are selected when clicking the OK button, the specified error message will appear:
<spuc:InputFormCheckBoxList ID="SampleInputFormCheckBoxList" runat="server" class="ms-authoringcontrols"> <asp:ListItem Text="Option 1" Value="1" /> <asp:ListItem Text="Option 2" Value="2" /> <asp:ListItem Text="Option 3" Selected="True" Value="3" /> <asp:ListItem Text="Option 4" Value="4" /> </spuc:InputFormCheckBoxList> <spuc:InputFormCheckBoxListValidator ID="SampleCheckBoxValidator" runat="server" ControlToValidate="SampleInputFormCheckBoxList" ErrorMessage="This is a sample error message." />
If you try to use it in combination with a InputFormCheckBox control, you will get an unclear error message (not informing you about the real problem) but when looking with Reflector into the code, it learns you that the control referenced in the ControlToValidate property is casted to an InputFormCheckBoxList control.
The InputFormCustomValidator control
If one of the previous validation controls does not suit your needs, you can define a custom validation function. You have the choice to define a client-side validation function or a server-side validation function, or combine both. Best practice is to perform server-side validation, even if you use a client-side check because some smartasses can try to bypass your client-side script.
This is an example of server-side validation:
<spuc:InputFormTextBox ID="UsernameTextBox" runat="server" class="ms-input" Title="Username" TextMode="SingleLine" Columns="60" /> <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; }
Properties inherited from the ASP.NET CustomValidator control:
- ControlToValidate: This property is required and must contain the id of the control to which this validator control applies.
- ClientValidationFunction: contains the name of the javascript function that needs to be executed.
- OnServerValidate: contains the name of the server-side function that needs to be executed.
- ErrorMessage: This property contains the error message that will be displayed when the validation fails.
- SetFocusOnError: When this property is set to true, the focus is set on the control that caused the validation to fail.
- EnableClientScript: Setting this property to false will bypass client-side validation.
A lot of people combine a custom validator control with a RequiredFieldValidator but this is not necessary because the ASP.NET CustomValidator control (and thus also the InputFormCustomValidator control) has a ValidateEmptyText property which can be set to true or false. If set to false, a blank entry is validated as a valid entry. If set to true, a blank entry will be considered as erroneous, thus excluding the need for a RequiredFieldValidator control.
If you want to use client-side validation, you have to set the ClientValidationFunction property. The value must be the name of a javascript function.
<spuc:InputFormTextBox ID="UsernameTextBox" runat="server" class="ms-input" Title="Username" TextMode="SingleLine" Columns="60" /> <spuc:InputFormCustomValidator ID="UsernameCustomValidator" runat="server" Display="Dynamic" SetFocusOnError="true" ControlToValidate="UsernameTextBox" ClientValidationFunction="IsValidUsername" ErrorMessage="Your user name must be at least 10 characters long (client-side validation)." ValidateEmptyText="true" />
The javascript function must reside in the <asp:Content> placeholder with ContentPlaceHolderID PlaceHolderMain (where most of your controls reside). The function needs 2 arguments: a source object, being the control that needs validation; and an arguments object having properties like Value and IsValid. If you want the validation to succeed, you have to set args.IsValid to true; if you want the validation to fail, you have to set args.IsValid to false.
<asp:Content ID="Main" runat="server" ContentPlaceHolderID="PlaceHolderMain"> <script language="javascript"> function IsValidUsername(source, args) { if (args.Value.length >= 10) args.IsValid = true; else args.IsValid = false; } </script> <!- - rest of the controls--> </asp:Content>
Important properties of the SharePoint InputFormCustomValidator control:
- Display: This property influences the postion of the subsequent controls. If set to Static, the necessary space for the error message will be foreseen. Possible values are None, Dynamic and Satic.
- ErrorImageUrl: If this property is filled out, the image will be displayed together with the error message in case a validation error occurs.
- BreakAfter: When this property is set to true, a linke break is inserted after the error message.
- BreakBefore: When this property is set to true, a line break is inserted before the error message.
ValidationSummary control
You can combine any SharePoint validation control with the ASP.NET ValidationSummary control. There is no counterpart for it in SharePoint.
When you use no ValidationSummary control, all error messages appear next to or right under the control that fails validation. A ValidationSummary control presents the user with a lsit of validation errors at the bottom of the page.
You add a ValidationSummary control to your application page or web part as follows:
<asp:ValidationSummary ID="SharePointValidationSummary" runat="server" DisplayMode="BulletList" ShowSummary="true" HeaderText="Please correct the following errors:" />
The different propeties on the ValidationSummary control are:
- DisplayMode: this property defines the appearance of the summary. Possible values are List, BulletList and SingleParagraph.
- HeaderText: set this property if you want to display a header text at the top of the summary.
- ShowSummary: set this property to show the error summary on the page. In that case the ShowMessageBox property must be set to false.
- ShowMessageBox: this property indicates whether the validation summary is displayed in a message box or on the page. In that case also the EnableClientScript property should be set to true.
Normally you should also be able to set the Text property of the SharePoint validation controls to f.e. * to display an asterisk next to the control that failed validation but after a look inside the Microsoft.SharePoint.dll with Reflector it show that the Text property is overridden and looses its original meaning.
[…] SharePoint Validation Controls […]
Pingback by SharePoint Validation Controls « Karine Bosch’s Blog | March 22, 2009 |
Karine,
Thanks for the nice article. This is useful reference material.
Tony Bierman [MVP WSS]
Comment by Tony Bierman [MVP WSS] | March 22, 2009 |
FANTASTIC!
Comment by Vasiansattiva | April 11, 2009 |
[…] One or more validators can be defined in Template_Metadata. Take a look at this gold post about the different validators that exist in […]
Pingback by Insert a CustomValidator in a SharePoint Form (New/Edit) | June 14, 2009 |
The best information i have found exactly here. Keep going Thank you
Comment by LnddMiles | July 22, 2009 |
Hi Karine,
Why don’t you use standard asp.net validators?
Thanks.
Comment by km | August 25, 2009 |
Km,
Why should I if they exist for SharePoint? The point of this blog section is about SharePoint controls?
Karine
Comment by Karine Bosch | August 25, 2009 |
Karine
Can you please share the code of ValidationSummary control?
I am not sure how to display label with textbox?
Avi
Comment by Avi | September 3, 2009 |
Hi Avi,
I’m not sure I understand your question. The validation summary lists a summary of error message and the code is at the bottom of the post.
Wich label and textbox do you mean?
Greetz,
Karine
Comment by Karine Bosch | September 4, 2009 |
Excellent job. Very useful.
To get the InputFormCustomValidator server side validation method to work, I had to modify the second parameter and cast the value as shown below.
protected void ValidateUserName(object source, EventArgs e)
{
ServerValidateEventArgs args = (ServerValidateEventArgs )e;
if (args.Value.Length >= 10)
args.IsValid = true;
else
args.IsValid = false;
}
Comment by Kirk Liemohn | September 25, 2009 |
Hi Karine,
Many thanks for this article. It is a good reference point. I would like to know if these validation controls can be used in a webpart where I have a custom form using normal controls like textboxes, checkboxlist etc.
If yes, where can I see some examples on How to use validation controls in custom webparts using sharepoint object model.
Thanks,
Comment by PrakashJJ | November 18, 2009 |
gr8 post..
Many thanks for this article….
Comment by chanakya | November 18, 2009 |
Hello Karine,
Can you tell me if these controls can be used in newform.aspx page ?
Looking forward to your reply.
Thanks,
Comment by PrakashJJ | November 26, 2009 |
Hi Prakash,
Yes, I suppose you can use these controls in f.e. the NewForm.aspx, but I don’t know why you would do so. NewForm.aspx and EditForm.aspx use RenderingTemplates defined in ascx control that you deploy to the CONTROLTEMPLATES folder. In these templates you can best use the CompositeField template that takes care of rendering the desired fields taking care of their corresponding data type.
Karine
Comment by Karine Bosch | November 26, 2009 |
Nice summary, thank you.
BTW, like CustomValidator, InputFormCustomValidator does NOT require a ControlToValidate. It can be triggered through the page Validate function on its own and thus be a multi-control validator.
Comment by Jon | December 9, 2009 |
Hi,
I am impressed by this article but i cant find and sharepoint validation controls in sharepoint designer. so could you help me explaining this article in more detail.
Comment by sweety | December 25, 2009 |
Such a wonderful article for sharepoint learners…
I hope in future you will publish more articles on your blogs related to the SharePoint technology..
Will be waiting for the next…
Thanks!!
Comment by Vijay | March 30, 2010 |
Hi Karine,
Please respond to the post above from PrakashJJ about using the controls in a custom web part. I have tried by adding the InputFormRequiredFieldValidator and when the web part renders I get an error. I get the same results with the standard asp required field validator. There must be something else I need to declare when adding these controls to a custom web part.
Comment by Guy | April 29, 2010 |
In your opinion, which question of PrakashJJ has been left unanswered?
Comment by Karine Bosch | April 29, 2010 |
Hats off to u…I was searching for this validation since long time..
Comment by Gaurav P | May 4, 2010 |
Sometimes one forgets that the simplest answer is the best answer and you reminded me of that! This page saved me from a lot of hassle as I was fighting validation. I totally forgot about these controls! Thanks!!
Comment by spevilgenius | May 27, 2010 |
How do you add this validation to an existing list with out changing the default application page.
Comment by Hector Caban | July 26, 2010 |
Hector,
I’m afraid you can’t. If you want to add additional validation controls to the New and/or Edit form of a list, you will have to create your own New and/or Edit form.
Karine
Comment by Karine Bosch | July 26, 2010 |
I found your post very usefull, thanks, but unfortunately it doesn’t work with InputFormRequiredFieldValidator as soon as it’s a multiline with richtext like this:
(with the same InputFormRequiredFieldValidator as your example)
I’m working with MOSS 2010. If you have any tips on what I should do to make this work I would be pleased.
Comment by Amelie | August 30, 2010 |
Hi Karine,
Article is good!!!
I’m using to accept date or time from user, can I use above mension validation control with the sharepoint control? if yes then how?
Thanks.
Comment by Poonam | September 1, 2010 |
Hi Karine
Excellent Post.Very informative
Thanks,
Comment by sri | September 22, 2010 |
Hey there
Is it possible to attach a HTML label with for attribute to sharepoint textbox
Comment by anurag | November 9, 2010 |
how to use these controls in edit it didn’t bind to any values so we can’t use it in dos[lay mode like note field
Comment by mustafa | January 17, 2011 |
Are there any validation controls specific for FormFields ?
How do you force to validate a field or skip a field from validation when in the custom edit form, the field objects are in the form of ‘FormField’
Comment by mano | April 4, 2011 |
Hi Mano,
For your FormFields (in Edit form or New form) the validation depends on the validation rules you defined for the fields. If f.e. you defined that a column in your list is required, a RequiredFieldValidValidator control is automatically added by the internals of the Microsoft.SharePoint.dll.
Karine
Comment by Karine Bosch | April 5, 2011 |
but the validation fires only with sharepoint:savebutton click, it doesn’t fire with default asp.net button, how to do that?
Comment by saboor (@sabor_11) | August 12, 2011 |
Can you give a bit more explanation why you want to use a default asp.net button instead of the SharePoint save button? You are getting a lot of troubles over your head.
Comment by Karine Bosch | August 12, 2011
[…] las directivas pre definidas en la página podemos acceder a ellos. Karine Bosch explica aquí cada uno de estos controles y lo hace muy bien. Favor de ver este post antes de […]
Pingback by Como validar campos en formularios de listas personalizadas de SharePoint con SharePoint Designer - Haaron Gonzalez | June 15, 2011 |
[…] directivas pre definidas en la página podemos acceder a ellos. Karine Bosch explica aquí cada uno de estos controles y lo hace muy bien. Favor de ver este post antes de […]
Pingback by Como validar campos en formularios de listas personalizadas de SharePoint con SharePoint Designer - Haaron Gonzalez | July 19, 2011 |
I am using this, but it is not working
Error :
Control ‘Date’ referenced by the ControlToValidate property of ‘InputFormCompareValidator2’ cannot be validated
Comment by saboor | August 12, 2011 |
I don’t think it’s a good idea to give controls a name like ‘Date’. Give it another name like f.e. StartDatePicker and put that in the ControlToValidate property.
Comment by Karine Bosch | August 12, 2011 |
Why would you use a default asp.net button instead of the SharePoint save button? You are getting a lot of trouble over your head if you want to make the save work with a default asp.net button.
Comment by Karine Bosch | August 12, 2011 |
Hi thanks for the good work
Do we have to convert the list form control to textbox control to get this .NET required filed validator working?
regards
Comment by John | October 21, 2011 |
Hi John,
What do you mean by “list form control”? Do you mean to customize the edit form? And do you want to use the .NET validation controls or the SharePoint validation controls?
Comment by Karine Bosch | October 22, 2011 |
Karin
Thank you for your propmpt reply.If I want this .Net validation control to work on the custom list it has to be formatted to text field.(correct me if i am not right?)
If I am right, I meant was if we need a dropdown list to be validated by this .net control,how to go about that.If you format the dropdown to text field it is no longer a dropdown control.
Any input i would highly appreciate
Thank you kindly
Comment by John | October 27, 2011 |
Hi ,
I am facing issue with the date time control and compare validator. I have a webpart in which i have created start and end datetimecontrol created in code behind. I am trying to validate whether end date is greater than start date using below code. But it is not working . please let me know what is wrong… I am not able to figure the problem
dateCompareValidator.ID = “dateCompareValidator”;
dateCompareValidator.ForeColor = System.Drawing.Color.Red;
dateCompareValidator.ControlToValidate = “datetimeto$datetimetoDate”;
dateCompareValidator.ControlToCompare = “datetimefrom$datetimefromDate”;
dateCompareValidator.ErrorMessage = “Please enter End Date greater than Or equal to start date”;
dateCompareValidator.Type = ValidationDataType.Date;
dateCompareValidator.Operator = ValidationCompareOperator.GreaterThanEqual;
dateCompareValidator.Display = ValidatorDisplay.Dynamic;
azcomparevalidatordiv.Controls.Add(dateCompareValidator);
Comment by ranjani | December 30, 2011 |
Hi Karine,
My issue got resolved after i gave LocaleId as shown below
codestartdate.LocaleId = 2057;
Comment by Ranjani | January 2, 2012 |
Thanks for this nice overview
Comment by Pascal Van Vlaenderen | February 16, 2012 |
Great overview…I need to use validation groups…do these controls support this? I have a save and submit button, save does not require validaiton but submit does…
Thanks,
Stephen
Comment by Stephen Davidson | June 18, 2012 |
Great article but i have a strange problem with the custom validator. I have a validator inside a WebPart and it triggers as it should. On the same page (SPWeb) i have a SPList with a Pager. When i click in the list (to change page) it also triggers the validation. I have tried with validation groups but nothing helps. Any ide how to solve this?
Thanks,
Mark
Comment by Mark | November 20, 2012 |
Mark,
I never tried it out but I’m affraid this is a SharePoint thing. But when your code runs, one of the incoming arguments is the source object. You can check on this object before you allow the validation code to run.
Kind regards,
Karine Bosch
Comment by Karine Bosch | November 21, 2012 |
[…] SharePoint Validation Controls « Karine Bosch’s Blog […]
Pingback by Resources: SharePoint Development,Programming And PowerShell | lionadi | March 18, 2013 |
Very useful, thanks!
Comment by Dani Milloc | August 21, 2013 |
can we add SharePoint:InputFormCustomValidator in NewForm.aspx? If yes than how to set the controltovalidte property for formfield “ff8{$Pos}”. Let me know if my reqt is not clear
Comment by raghu | August 22, 2013 |
Hi Karine,
The article was excellent. Can you please guide me how to do validation in DateTime Control?
Vaishnavi k
Comment by Vaishnavi | January 21, 2015 |