Skip to main content

SharePoint 2013 Date time field validation using client side rendering(CSR)


Recently one of the client has asked for validation to the date time field in a list. Published date time value should be greater than today and expiry date should be less than published date. Client wants the error message to be shown similar to the way how share point shows the error messages. Client side rendering(CSR) came to my rescue.

Using CSR the developers have more control on what to show and how to show. I dont want to go into what is CSR and also those things. If you want to find out CSR read this article CSR basics.

First we will be creating a field and add some js links to it. 
// Create a field and add the required js link.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">  
  
 <Field Type="Text"
   Name="DateVal"
   Description="Enter Publishing Date"
   DisplayName="Expiry Date"
   StaticName="DateVal"
   Group="JSLink Site Columns"
   Hidden="FALSE"
   Required="FALSE"
   JSLink="~layouts/MJH.JSLink/jquery-1.10.2.min.js|~layouts/datepicker.js|~layouts/MJH.JSLink/CalendarColumnRendering.js"     
   ID="{00C72E88-AFF0-4C81-B24F-570F70127ABE}">
</Field>
</Elements>

In the above i created a field of type text and added some js links to it. CalendarColumnRendering.js file contains my CSR code. The js files before are the supporting ones. Even though the field type is text we will be rendering a date time html.

 Create the required js file.


//CalendarColumnRendering.js file
(function () {
    var test = {};
    test.Templates = {};
    test.Templates.Fields = {        
        'DateVal': { 'NewForm': datePickerFieldTemplate }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(test);
})();



function datePickerFieldTemplate(ctx) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
    var colid = formCtx.fieldSchema.Id;
    var colName = formCtx.fieldSchema.Name;
    var webUrl = formCtx.webAttributes.WebUrl;
    formCtx.registerGetValueCallback(formCtx.fieldName, returnVal.bind(null, formCtx.fieldSchema));

    var validators = new SPClientForms.ClientValidation.ValidatorSet();
    validators.RegisterValidator(new dateTimeValidator());

    formCtx.registerValidationErrorCallback(formCtx.fieldName, errorMessage);
    formCtx.registerClientValidator(formCtx.fieldName, validators);

    return renderHtml(colid, colName, webUrl);
}

function returnVal(fieldSchema) {
    var colname = fieldSchema.Name;
    var colid = fieldSchema.Id;
    var id = "#" + colname + "_" + colid + "_DateTimeFieldDateHours option:selected";
    var hrval = $(id).text();
    id = "#" + colname + "_" + colid + "_DateTimeFieldDateMinutes option:selected";
    var minval = $(id).val();
    var hrvals = hrval.split(" ");
    return $("input[id*='" + colname + "']").val() + " " + hrvals[0] + ":" + minval + " " + hrvals[1];
}


dateTimeValidator = function () {
    dateTimeValidator.prototype.Validate = function (value) {
        
            var isError = false;
            var errorMessage = "";
            var x = value.split(" ");
            var date = null;
            var time = null;
            if (x[2] == 'PM') {
                var y = x[1].split(':');
                time = (parseInt(y[0]) + 12) + ":" + y[1];
            } else {
                time = x[1];
            }

            date = x[0];

        if (date.length > 0) {
            if (new Date() > new Date(date + " " + time)) {
                isError = true;
                errorMessage = "Expiry Date should be greater than today";
            }
        } else {
            isError = true;
            errorMessage = "Expiry Date cannot be empty.";
        }

        return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
    };
};

function errorMessage(error) {
    $('#serror').html(error.errorMessage + '<br>').css('color', '#bf0000');
}

This is the final output which i got.












Please find link to the complete code.


Comments

Popular posts from this blog

Sharepoint 2013 REST API limitations with site columns

Recently i attended an interview for one of the company, the interviewer asked me a question on rest api. How to get a publishing image field using rest api? I answered its the normal way how we get the other fields. But later i came to know that its the wrong answer. After some research on Google came to know that there some limitations to rest api in sharepoint 2013. Below is a list of columns available using Rest api. Column Support Notes Hyperlink or Picture Supported Single Line of Text Supported Multiple lines of text :: Plaintext Supported Multiple lines of text :: Richtext Supported Returns unencoded XHTML Multiple lines of text :: Enhanced Richtext Supported Returns unencoded XHTML Choice Supported Column is required in the  $expand  keyword Counter Supported Integer Supported Number Supported Currency Supported Date Supported Returns an ISO 8601 date e.g. 2013-03-08T11:00:00 Yes/No Supported Returns true or false string literals Person or Group Suppo...

How to upgrade typescript version in a SPFX solution

Why do we need to upgrade typescript version in a SPFX solution? As part of SPFX development we try to install 3 rd party libraries, there is a possibility that we might face type errors. For example, if we try to install ANTD package as part of your solution and use one of its components and try to build the solution. You might be seeing the type errors (TS1005,TS1109) as shown below. Typescript errors How to find out the typescript version? When you build (Gulp build) the SPFX solution you will be able to find out the typescript version from the build log as shown below.  Steps for updating the Typescript version. In SPFX solution typescript version has dependency on the @Microsoft/rush-stack-compiler package version.  In the package.json if you have @microsoft/rush-stack-compiler-2.7 then the typescript version is 2.7.x.    In the SPFX solution deleted the node_modules folder. It will remove all the packages that are installed....

Use of Expression in Microsoft flow through an example

Most of the basic flows can be configured using the templates provided by Microsoft. But in real time we will be developing flows which have complexity. Expression play an important role in fulfilling the requirements. Scenario : -  We have project details list which has the below columns, we need to intimate the project team before 2 days of the end date. (Please note that this scenario is picked up from one of the Microsoft insight demo) The following points needs to be implemented ·          Only title and End time are mandatory fields, Start time if not entered needs to be taken as the current date. ·          Number of days is the difference between the start time and end time.   ·          Email needs to be sent before 2 days of the end date. ·          If any attachments they nee...