Introduction to Client Forms Validation in SharePoint 2013

Client side event handlers in SharePoint

In addition to server side Event Model,  SharePoint also provides client side  event handling capabilities when working with List Forms.

Let’s see briefly how it works. In List Forms pages Save button click handler triggers PreSaveItem function , PreSaveItem function is declared in forms.js:

function PreSaveItem()
{
if ("function"==typeof(PreSaveAction))
{
return PreSaveAction();
}
return true;
}

view raw
PreSaveItem.js
hosted with ❤ by GitHub

PreSaveAction function from another hand, is a user defined function that allows to override standard behavior for a Save button handler, so in terms of server side event model it is a binding mechanism.

I find this mechanism  pretty convenient for implementing custom client side validation in List Forms,  the following example demonstrates how to implement client side validation for Email field in Contacts list:

function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function PreSaveAction(){
var emailBox = getFieldControl('Email','Text');
if (!validateEmail(emailBox.val())) {
var errorHtml = '<span class="ms-formvalidation"><span role="alert">Invalid email address<br></span></span>';
emailBox.after(errorHtml);
return false;
}
return true;
}
function getFieldControl(fieldName,fieldType)
{
var control = $('[id^=' + fieldName + '_][id$=' + fieldType + 'Field]');
return control;
}

view raw
PreSave.js
hosted with ❤ by GitHub

EmailValidate

Client forms validation in SharePoint 2013

In SharePoint 2013 as part of  Client-Side Rendering (CSR), there is SPClientForms.ClientValidation  namespace (clientforms.js) that contains  types and objects for performing  client side validation in List Forms. For example,

SPClientForms.ClientValidation.RequiredValidator object is intended for evaluating the value of an field control to ensure that the user enters a value (it  is invoked for a fields when SPField.Required property is set to True):

SPClientForms.ClientValidation.RequiredValidator = function() {
};
SPClientForms.ClientValidation.RequiredValidator.prototype.Validate = function(value) {
value = SPClientTemplates.Utility.Trim(value);
var hasError = value === '';
var errorMsg = hasError ? Strings.STS.L_SPClientRequiredValidatorError : '';
return new SPClientForms.ClientValidation.ValidationResult(hasError, errorMsg);
};

Below is provided a complete example that demonstrates how to implement  client-side validation for Email field in Contacts list:

CustomClientValidation = {};
CustomClientValidation.EmailValidator = function() {
};
CustomClientValidation.EmailValidator.prototype.Validate = function(value) {
value = SPClientTemplates.Utility.Trim(value);
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var hasError = !re.test(value);
var errorMsg = hasError ? 'Invalid email address' : '';
return new SPClientForms.ClientValidation.ValidationResult(hasError, errorMsg);
};
function EmailField_Edit(rCtx) {
if (rCtx == null)
return '';
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx);
if (formCtx == null || formCtx.fieldSchema == null)
return '';
var _value = formCtx.fieldValue != null ? formCtx.fieldValue : '';
if (_value.length > 0) {
var validators = new SPClientForms.ClientValidation.ValidatorSet();
validators.RegisterValidator(new CustomClientValidation.EmailValidator());
formCtx.registerClientValidator(formCtx.fieldName, validators);
}
return SPFieldText_Edit(rCtx); //default renderer for Text field
}
(function () {
var emailFieldCtx = {};
emailFieldCtx.Templates = {};
emailFieldCtx.Templates.Fields = {
'Email': {
'NewForm': EmailField_Edit,
'EditForm': EmailField_Edit
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(emailFieldCtx);
})();

Key points:

  • CustomClientValidation.EmailValidator object implements a custom validation  for Email field
  • since Email field is a standard Text Field,  the rendering of field control is reused, only custom validator is registered for a field (see function EmailField_Edit for a details)