使用 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 部件屬性和頁面。