Sunday, December 27, 2009

验证输入空间 - 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.

inputformrequiredfieldvalidator


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.

inputformrangevalidator


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.

inputformcomparevalidator





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:


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.

inputformregexvalidator


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:

inputformcheckboxvalidator







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.

inputformcustomvalidator-serverside

This is an example of server-side validation:


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.

inputformcustomvalidator-clientside


The javascript function must reside in the 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.




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.

validationsummary

You add a ValidationSummary control to your application page or web part as follows:

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 延伸 Global.asax - Extending SharePoint using Global.asax

Have you ever wanted to do stuff with SharePoint sites that webparts just won't let you do? Here are a few things that I wanted to do in SharePoint that I knew I couldn't really do with WebParts or custom pages.

  • Better stats - the built-in stats are ok, but I want some better stats.
  • Register Users - I want everyone to have access to the site, but I would like to collect a little information about them before I give them access.

For this article I will just tackle the task of getting better stats about SharePoint usage, but you can easily apply the methods I use to do all kinds of things in your SharePoint application.

First off, you will need to do a little background reading on Global.asax (if you aren't already familiar with it). The Global.asax file allows you to write code against events that happen within an ASP.Net application. SharePoint is no different so you can write custom code and stick it in the Global.asax file and gain more control over your application.

Below is a quick and dirty solution for capturing information about how people are using your SharePoint site (or portal). Of course you can use the built in stats, however, I personally find those stats to be somewhat limited. The method below captures the URL the person went to, the timestamp of the request, and the UserID. What you can do is to add this code to a file called Global.asax and place it in the root directory of your site.

<%@ Application ClassName="Globals" language="c#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web" %>

Before you can use the script you will also need to create a table and a stored procedure to populate the table. Below is the SQL script to create both. You will need to put them in a custom database (I would not recommend putting them in one of the SharePoint databases).

create table [Hits]
(
Url varchar(256) NOT NULL,
UserID varchar(50) NOT NULL,
Timestamp datetime NOT NULL
)
go
create proc Hit_Add
(
@Url varchar(256),
@UserID varchar(50)
)
as
insert into Hits values
(@Url, @UserID, getdate())

go

That's all there is to it. The AuthenticateRequest Event gets fired each time the user makes a request to the site. You make the call to the database here because in the BeginRequest event the user hasn't been authenticated yet. I'm not sure but I believe this is different from normal ASP.Net applications due to the way SharePoint handles the request.

I'm sure you can think of many other ways that this will be useful. I'll be looking forward to your comments and suggestions.