Suppose we have a SharePoint list and it has four fields viz. Title, Full Name, Email, Mobile Number etc. Now if you want to apply custom validation in New/Edit Item form, you can easily do it with CSR code. The below mentioned can validate following conditions in forms:
Step : 1 Create a JS file, say CSRValidations.js
and copy paste following code in the JS file
(function () {
// Create object that have the context information about the field that we want to change it's output render
var fieldContext = {};
fieldContext.Templates = {};
fieldContext.Templates.Fields = {
// Apply the new rendering for Email field on New and Edit Forms
"Title": {
"NewForm": titleFieldTemplate,
"EditForm": titleFieldTemplate
},
"Full_x0020_Name": {
"NewForm": fullNameFieldTemplate,
"EditForm": fullNameFieldTemplate
},
"Email": {
"NewForm": emailFieldTemplate,
"EditForm": emailFieldTemplate
},
"Mobile_x0020_Phone": {
"NewForm": mobilePhoneFieldTemplate,
"EditForm": mobilePhoneFieldTemplate
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldContext);
})();
// This function provides the rendering logic
function emailFieldTemplate(ctx) {
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
// Register a callback just before submit.
formCtx.registerGetValueCallback(formCtx.fieldName, function () {
return document.getElementById('inpEmail').value;
});
//Create container for various validations
var validators = new SPClientForms.ClientValidation.ValidatorSet();
validators.RegisterValidator(new emailValidator());
// Validation failure handler.
formCtx.registerValidationErrorCallback(formCtx.fieldName, emailOnError);
formCtx.registerClientValidator(formCtx.fieldName, validators);
return "<span dir='none'><input type='text' value='" + formCtx.fieldValue + "' maxlength='255' id='inpEmail' class='ms-long'> \ <br><span id='spnEmailError' class='ms-formvalidation ms-csrformvalidation'></span></span>";
}
// Custom validation object to validate email format
emailValidator = function () {
emailValidator.prototype.Validate = function (value) {
var isError = false;
var errorMessage = "";
//Email format Regex expression
//var emailRejex = /\S+@\S+\.\S+/;
var emailRejex = /^(([^<>()[\]HYPERLINK "\\.,;:\s@\"\\.,;:\s@\"]+(\.[^<>()[\]HYPERLINK "\\.,;:\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,}))$/;
if (value.trim() == "") {
isError = true;
errorMessage = "You must specify a value for this required field.";
}else if (!emailRejex.test(value) && value.trim()) {
isError = true;
errorMessage = "Please enter valid email address";
}
//Send error message to error callback function (emailOnError)
return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
};
};
// Add error message to spnError element under the input field element
function emailOnError(error) {
document.getElementById("spnEmailError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}
// This function provides the rendering logic
function titleFieldTemplate(ctx) {
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
// Register a callback just before submit.
formCtx.registerGetValueCallback(formCtx.fieldName, function () {
return document.getElementById('inpTitle').value;
});
//Create container for various validations
var validators = new SPClientForms.ClientValidation.ValidatorSet();
validators.RegisterValidator(new titleValidator());
// Validation failure handler.
formCtx.registerValidationErrorCallback(formCtx.fieldName, titleOnError);
formCtx.registerClientValidator(formCtx.fieldName, validators);
return "<span dir='none'><input type='text' value='" + formCtx.fieldValue + "' maxlength='255' id='inpTitle' class='ms-long'> \ <br><span id='spnTitleError' class='ms-formvalidation ms-csrformvalidation'></span></span>";
}
// Custom validation object to validate title format
titleValidator = function () {
titleValidator.prototype.Validate = function (value) {
var isError = false;
var errorMessage = "";
if (value.trim() == "") {
isError = true;
errorMessage = "You must specify a value for this required field.";
}
//Send error message to error callback function (titleOnError)
return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
};
};
// Add error message to spnError element under the input field element
function titleOnError(error) {
document.getElementById("spnTitleError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}
// This function provides the rendering logic
function mobilePhoneFieldTemplate(ctx) {
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
// Register a callback just before submit.
formCtx.registerGetValueCallback(formCtx.fieldName, function () {
return document.getElementById('inpMobilePhone').value;
});
//Create container for various validations
var validators = new SPClientForms.ClientValidation.ValidatorSet();
validators.RegisterValidator(new mobilePhoneValidator());
// Validation failure handler.
formCtx.registerValidationErrorCallback(formCtx.fieldName, mobilePhoneOnError);
formCtx.registerClientValidator(formCtx.fieldName, validators);
return "<span dir='none'><input type='text' value='" + formCtx.fieldValue + "' maxlength='255' id='inpMobilePhone' class='ms-long'> \ <br><span id='spnMobilePhoneError' class='ms-formvalidation ms-csrformvalidation'></span></span>";
}
// Custom validation object to validate mobilePhone format
mobilePhoneValidator = function () {
mobilePhoneValidator.prototype.Validate = function (value) {
var isError = false;
var errorMessage = "";
//MobilePhone format Regex expression
//var mobilePhoneRejex = /\S+@\S+\.\S+/;
var mobilePhoneRejex = /^[0-9]+$/;
if (value.trim() == "") {
isError = true;
errorMessage = "You must specify a value for this required field.";
}else if (!mobilePhoneRejex.test(value) && value.trim()) {
isError = true;
errorMessage = "Please enter valid mobile phone number";
}
//Send error message to error callback function (mobilePhoneOnError)
return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
};
};
// Add error message to spnError element under the input field element
function mobilePhoneOnError(error) {
document.getElementById("spnMobilePhoneError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}
// This function provides the rendering logic
function fullNameFieldTemplate(ctx) {
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
// Register a callback just before submit.
formCtx.registerGetValueCallback(formCtx.fieldName, function () {
return document.getElementById('inpFullName').value;
});
//Create container for various validations
var validators = new SPClientForms.ClientValidation.ValidatorSet();
validators.RegisterValidator(new fullNameValidator());
// Validation failure handler.
formCtx.registerValidationErrorCallback(formCtx.fieldName, fullNameOnError);
formCtx.registerClientValidator(formCtx.fieldName, validators);
return "<span dir='none'><input type='text' value='" + formCtx.fieldValue + "' maxlength='255' id='inpFullName' class='ms-long'> \ <br><span id='spnFullNameError' class='ms-formvalidation ms-csrformvalidation'></span></span>";
}
// Custom validation object to validate fullName format
fullNameValidator = function () {
fullNameValidator.prototype.Validate = function (value) {
var isError = false;
var errorMessage = "";
//FullName format Regex expression
var fullNameRejex = /^[a-z ,.'-]+$/i;
if (value.trim() == "") {
isError = true;
errorMessage = "You must specify a value for this required field.";
}else if (!fullNameRejex.test(value) && value.trim()) {
isError = true;
errorMessage = "Please enter valid name";
}
//Send error message to error callback function (fullNameOnError)
return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
};
};
// Add error message to spnError element under the input field element
function fullNameOnError(error) {
document.getElementById("spnFullNameError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}
Step : 2 Open New Item Form in browser. Edit page and edit web part.
Step : 3 In Web part properties, Go to Miscellaneous --> JS link --> paste the path of your js file (e.g. ~sitecollection/SiteAssets/CSRValidations.js)
Step : 4 Save Web part properties and page.