Export (0) Print
Expand All

How to: Implement Custom Validation in the JS Grid Control

SharePoint 2010

Learn how to programmatically add custom validation to a JS Grid control by using a custom property type.

Last modified: November 29, 2011

Applies to: SharePoint Foundation 2010

You can add validation to a custom JS Grid control by using a custom property type that defines the validation logic. Validation ensures that cell values are entered in the correct format.

To add validation to the JS Grid control, perform the following high-level steps:

  • Create and register a custom property type that defines validation logic (and optionally register custom controls)

  • Assign the property type to grid fields

The procedure in this topic creates and registers a custom property type that derives from a built-in property type and uses a regular expression to validate user input in specific columns. The validation applies to a custom JS Grid control Web Part, which you create by following the procedure in How to: Write Back Changes from the JS Grid Control. (This topic was written by Sivaraman Krishnan, Microsoft Corporation.)

Note Note

Although you can complete this procedure without using Visual Studio 2010, it is easier if you use both Visual Studio 2010 and the SharePoint development tools in Microsoft Visual Studio 2010. Your computer might show different names or locations for some Visual Studio 2010 user-interface elements in the following instructions. The Visual Studio 2010 edition that you have and the settings that you use determine these elements.

To implement custom validation in a JS Grid control, create and register a custom property type that defines validation logic and then apply the custom property type to grid fields.

You can register a custom property type by using one of the following functions:

  • RegisterNewCustomPropType   Registers a custom property type and specifies the custom controls to use with the property type. (To register custom controls, use the following functions: RegisterDisplayControl, RegisterEditControl, and RegisterWidgetControl.)

  • RegisterNewDerivedCustomPropType   Registers a custom property type that uses the default controls of the base property type. Base property types include String, JSNumber, MultiValuePropType, Hyperlink, and CheckBoxBoolean.

  • RegisterNewLookupPropType   Registers a custom property type that derives from the LookUpTable property type.

These functions are defined in the SP.JsGrid.PropertyType namespace and the SP.JsGrid.PropertyType.Utils namespace in the jsgrid.debug.js file, which is located in the default path %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS.

To create and register a custom property type

  1. In Visual Studio, open the JSGridWritebackWebPart solution that you created in How to: Write Back Changes from the JS Grid Control.

  2. Open JSGridWritebackManager.js.

  3. Paste the following code at the end of the JSGridWritebackManager.js file.

    // Create and register the AllowOnlyAlphabet custom property type.
    function RegisterAllowOnlyAlphabetPropType() {
    
        // Derive from the String property type.
        var basePropType = SP.JsGrid.Internal.Property.GetPropType('String');
        var AllowOnlyAlphabetPropType = SP.Internal.JS.object(basePropType);
    
        AllowOnlyAlphabetPropType.ID = 'AllowOnlyAlphabet';
    
        // Define the validation logic. This example uses a regular expression
        // to specify that only letters and spaces are allowed.
        AllowOnlyAlphabetPropType.BeginValidateNormalizeConvert = function (
            recordKey, fieldKey, newValue, bIsLocalized, fnCallback, fnError) {
            basePropType.BeginValidateNormalizeConvert.apply(this, [recordKey, 
                fieldKey, newValue, bIsLocalized, PostProcess, fnError]);
            function PostProcess(result) {
                result.isValid = result.isValid;
                result.dataValue = result.normalizedLocValue = newValue == '' ? null : newValue;
                var regexLetter = /^[a-zA-Z ]+$/;
                if (!regexLetter.test(newValue)) {
                    result.isValid = false;
                    result.errorMsg = 'Only letters and spaces are allowed for this field.';
                }
                fnCallback(result);
            }
        };
        SP.JsGrid.PropertyType.RegisterNewDerivedCustomPropType(AllowOnlyAlphabetPropType, 'String');
    }
    

    This code creates the custom AllowOnlyAlphabet property type, defines the validation logic, and registers the property type.

  4. In the Init method, paste the following code after the _props variable declaration.

    // Register the AllowOnlyAlphabet property type.
    RegisterAllowOnlyAlphabetPropType();
    

    The Init method should resemble the following example.

    this.Init = function (jsGridControl, initialData, props) {
        _jsGridControl = jsGridControl;
        _props = props;
    
        // Register the AllowOnlyAlphabet property type.RegisterAllowOnlyAlphabetPropType();
    
        // This event is triggered after the standard grid error checking.
        jsGridControl.AttachEvent(SP.JsGrid.EventType.OnCellEditCompleted, OnCellEditCompleted);
    
        BindJSGrid(CMD_SHOW_PROJECTS);
    
        window.onbeforeunload = function () {
            if (WGM.IsSaveProjectsEnabled()) {
                return "Changes on this page haven't been saved. If you continue, the changes will be lost."
            }
        }
    }
    

    This code calls the RegisterAllowOnlyAlphabetPropType function to register the custom property type when the JS Grid control is initialized. The next step is to apply the custom property type to specific grid fields.

To apply the custom property type to grid fields

  1. Open GridUtilities.cs.

  2. In the formatGridField method, replace gf.PropertyTypeId = "String"; with the following code.

    // Apply the custom property type to Name fields. 
    switch (gf.FieldKey)
    {
        case "FirstName":
        case "MiddleName":
        case "LastName":
            gf.PropertyTypeId = "AllowOnlyAlphabet";
            break;
        case "Title":
        case "EmailAddress":
        case "Phone":
        default:
            gf.PropertyTypeId = "String";
            break;
    }
    

    This conditional statement sets the property type of GridField objects based on the name of the corresponding GridColumn object. It sets grid fields for the FirstName column, the MiddleName column, and the LastName column to the AllowOnlyAlphabet property type and sets all other grid fields to the String property type.

To test the custom validation in the JSGridWritebackWebPart Web Part

  1. Deploy the JSGridWritebackWebPart project. The SharePoint site opens after the project deploys, and the JSGridWritebackWebPart Web Part is automatically added to the SharePoint 2010 Web Part gallery.

  2. Open any Web Parts page.

  3. On the Page tab, choose the Edit button.

  4. On the Insert tab, choose Web Part, choose the Custom category, and then add the JSGridWritebackWebPart from the custom category.

  5. On the Page tab, choose the Save & Close button. The page displays the Web Part.

  6. Edit the value of a first name, middle name, or last name to include numeric characters. To edit a value of a grid cell, give the cell focus, enter a value, and then move the focus to another cell.

    The grid row header displays a red error icon to indicate that the row contains an invalid cell value. To read the error message, either click the icon on the row header or click the icon that appears when the invalid cell (outlined in red) has the focus. If a row contains more than one error, you can click the icon on the row header to toggle through the error messages.

    Note Note

    If an earlier version of the JSGridWritebackManager.js file is cached, delete the temporary Internet files in your browser.

Show:
© 2014 Microsoft