使用 CSR 在 NewEdit 项目表单上应用验证
假设我们有一个 SharePoint 列表,它有四个字段即。标题,全名,电子邮件,手机号码等。现在,如果要在“新建/编辑项目”表单中应用自定义验证,可以使用 CSR 代码轻松完成。以下提到的可以在表格中验证以下条件:
- 字段中的空白值
- 电子邮件 ID 格式检查与正则表达式
- 手机号码格式检查正则表达式
- 全名字段不应包含数值
步骤:1 创建一个 JS 文件,比如说 CSRValidations.js
并在 JS 文件中复制粘贴代码
(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>";
}
步骤:2 在浏览器中打开新项目表单。编辑页面并编辑 Web 部件。
步骤:3 在 Web 部件属性中,转到其他 - > JS 链接 - >粘贴 js 文件的路径(例如~sitecollection / SiteAssets / CSRValidations.js)
步骤:4 保存 Web 部件属性和页面。