JSLink and Display Templates Part 4 – Validating user input

In the previous posts we have looked at JSLink and how we can use it, we have looked at overriding the rendering of individual fields both for display and also for editing. Now we are going to look at Validators and how we can validate user input before their changes are saved.

In order for a validator to work you need three moving parts:

  • Validation method (to tell SharePoint if the field input is valid or not)
  • OnError method (to handle any errors which are raised)
  • Registration code to do the plumbing

Validation Method
We’ll base this sample on the Custom Editing interface we built in Part 3 and first off we will build ourselves a validation method.

This is technically going to be an object with a Validate method (to which SharePoint will pass a value). The code for this method is as follows:

mjh.MyCustomFieldValidator = function () {
  mjh.MyCustomFieldValidator.prototype.Validate = function (value) {
    var isError = false;
    var errorMessage = "";

    if (value == "Item 2") {
      isError = true;
      errorMessage = "You cannot select 'Item 2'";
    }
    returnnew SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
  };
};

 

The code above contains a very simple if statement to check the items value (in my example saying that an error message will be displayed if the item value is set to “Item 2” .. one of the drop-down choices from Part 3 of this series).

Finally we call the SPClientForms.ClientValidation.ValidationResult method passing in our “isError” (a true/false boolean) and the error message (a text string).

OnError Method
We then need a final method which tells SharePoint basically what to do when an error actually occurs. This is a fairly simple method in which you can basically do whatever you want (pop-up alerts, add HTML to the page, change CSS, whatever you need).

Now we could just use an Alert(error.message) function if we wanted a particularly crude error message but it would be much better to have some formatted error message just like SharePoint does out of the box .. and for that to work we first need to have ourselves a recognisable element that we can manipulate using jQuery, so we add the following code to our rendering method for the edit interface:

// add the error span
returnHtml += "<span id='MyCustomFieldError' class='ms-formvalidation ms-csrformvalidation'></span>";

Once we have this we can manipulate it in our "onError" function (which as you can see is very simple).

mjh.onError = function (error) {
  $("#MyCustomFieldError")
  .html("<span role='alert'>" + error.errorMessage + "</span>");
};

 

So all we are really doing is grabbing the span using the ID we gave it, then injecting our error message.

Now for the plumbing …
So the only thing missing is making this all hang together from inside our render method: 

var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

// register the field validators
var fieldValidators = new SPClientForms.ClientValidation.ValidatorSet();

if (formCtx.fieldSchema.Required) {
  fieldValidators.RegisterValidator(
    new SPClientForms.ClientValidation.RequiredValidator()
  );
} fieldValidators.RegisterValidator(new mjh.MyCustomFieldValidator());

formCtx.registerValidationErrorCallback(formCtx.fieldName, mjh.onError);
formCtx.registerClientValidator(formCtx.fieldName, fieldValidators);

 

So lets walk through what we are doing in the code above.

First off we create ourselves a new ValidatorSet which will contain the validators that we need for the field. We then do a simple check to see if it is a required (mandatory) field and if it is we add the standard SharePoing “RequiredValidator” to our ValidatorSet.

Then we add our own new “MyCustomFieldValidator” object to the validator set.

Finally we have two register methods. The first one registerValidationErrorCallback is basically telling SharePoint that if our field fails validation that it should call the mjh.onError method to deal will letting the user know what has gone wrong.

The second one registerClientValidator actually registers our validators with SharePoint for the chosen field.

Note – it is perfectly possible to register your client validator without providing a validation error callback. If you do this then the validator will stop the form from being saved but the user won’t be told why (they’ll just get a frustrating form which won’t post back).

So ..  assuming all of the above has worked correctly you would see something like this if you tried to selected “Item 2”:

Validation message being shown in SharePoint

So that should be what you need to start putting together your own custom validation. You can of course use this technique on any number of fields.

For the complete code-sample to date (including Parts 2 and 3) please download the Visual Studio solution here:

https://sdrv.ms/15eB6CI

posted @ 2019-05-30 15:49  乘奔御风  阅读(121)  评论(0编辑  收藏  举报