Reusable Validation Method In SPFx

In this article, you will learn about reusable validation method in SPFx.

Recently I have implemented one reusable functions to validate the form in SPFx. In SPFx, we have so many react modules available in the market, but if we need some basic validation like required and regular we should install complete components into our solution and it will directly cause performance.
 

Develop SharePoint Framework Web Part

 
Open a command prompt. Create a directory for the SPFx solution.
 
md reusableformvalidations
 
Navigate to the above-created directory.
 
cd reusableformvalidations
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Yeoman generator will present you with the wizard by asking questions about the solution to be created. 
 
Reusable Validation Method In SPFx
 
Solution Name - Hit enter to have default name (reusableformvalidations in this case) or type in any other name for your solution.
Selected choice: Hit enter
 
Target for the component - Here we can select the target environment where we are planning to deploy the client web part i.e. SharePoint Online or SharePoint On-Premises (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files - We may choose to use the same folder or create a sub-folder for our solution.
Selected choice: Same folder
 
Deployment option - Selecting Y will allow the app to be deployed instantly to all sites and will be accessible everywhere.
Selected choice: Y
 
Type of client-side component to create - Generator will only allow you to create a web part.
Selected choice: WebPart
 
Web part name - Hit enter to select the default name or type in any other name.
Selected choice: reusableformvalidations
 
Web part description - Hit enter to select the default description or type in any other value.
Selected choice: ””.
 
Framework to use - Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout)
Selected choice:React Framework
 
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
 
npm shrinkwrap
 
In the command prompt type the below command to open the solution in the code editor of your choice.
 
code .
 
I am choosing to do very basic validations so I have created the below list of columns for the SharePoint list.
 
List Name - Employee Details.
 
Columns
 
First Name
Single Line of Text (internal name will be FirstName)
Last Name
Single Line of Text(internal name will be LastName)
Department
Choice with (HR, IT, Admin) (internal name will be Department)
Gender
Choice with (Male, Female) (internal name will be Gender)
Mobile Number
Number (internal name will be MobileNumber)
 
I have implemented the below reusable method which will accept data and fields as the below format.
  1. inValidDataMsgs: { "CategoryId required""Please Select Agenda Category""Title required""Please enter Title" },  
  2.       validationFields: {  
  3.         "required": ["CategoryId""Title"]  
  4.       },  
  5.   
  6. Calling   
  7. let validationResult = CommonMethods.ValidateForm(this.state.item, this.state.validationFields);  
  8.   
  9.     if (validationResult["isValid"]) {  
  10. }  
  11. else {  
  12.       let validationMsg = "";  
  13.       let msgs = this.state.inValidData;  
  14.       for (let vMsg in validationResult) {  
  15.         if (validationResult.hasOwnProperty(vMsg) && vMsg != "isValid")  
  16.           validationMsg += msgs[validationResult[vMsg]] + "\n";  
  17.       }  
  18.       alert(validationMsg);  
  19.     }  
Reusable Class
  1. export default class CommonMethods {  
  2.   public static ValidateForm(data, fields) {  
  3.     let validationCheckResult = { isValid: true };  
  4.     let isValid = true;  
  5.     for (let optType in fields) {  
  6.       switch (optType) {  
  7.         case "required":  
  8.           for (let fieldIndex = 0; fieldIndex < fields[optType].length; fieldIndex++) {  
  9.             let currentValue = data[fields[optType][fieldIndex]];  
  10.             if (!currentValue || currentValue == -1 || (Array.isArray(currentValue) && currentValue.length == 0)) {  
  11.               validationCheckResult[fields[optType][fieldIndex]] = fields[optType][fieldIndex] + " required";  
  12.               isValid = false;  
  13.             }  
  14.           }  
  15.           break;  
  16.         case "regular":  
  17.           for (let fieldKey in fields[optType]) {  
  18.             if (fields[optType].hasOwnProperty(fieldKey)) {  
  19.               if (!validationCheckResult[fieldKey]) {  
  20.                 let regExp = new RegExp(fields[optType][fieldKey]);  
  21.                 let result = regExp.test(data[fields[optType][fieldKey]]);  
  22.                 if (!result) {  
  23.                   isValid = false;  
  24.                   validationCheckResult[fieldKey] = fieldKey + " is not Valid";  
  25.                 }  
  26.               }  
  27.             }  
  28.           }  
  29.           break;  
  30.       }  
  31.       validationCheckResult["isValid"] = isValid;  
  32.   
  33.     }  
  34.     return validationCheckResult;  
  35.   }  
  36. }  
For complete usage, please download the attachment.