How To Apply Custom Validation On A SharePoint Form (New And Edit)

I was asked to add additional columns to a SharePoint “Out Of The Box (OOTB) calendar list with the aim of allowing the end user to complete each field in an orderly fashion.
 
The default field allows the user to reveal child fields based on the value of the previous field.
 
The fields in essence have a hierarchical structure. I decided to use a dropdown field (at least at the first two levels) to allow the user to jump from one selection to another. The last level can be any type of field. Before writing code, I executed the following steps,
  1. Create a “.html” file.
  2. Create a list (any type). In this case, I’m working with a Calendar list.
  3. In this list, I created four columns using the list settings. The column names are;
    • “Type of Events”
    • “Festivals”
    • “Parties”
    • “Galas”
  1. Add a Content Editor Web Part (CEWP) to the NewForm.aspx and EditForm.aspx files of your list.
  2. Edit each page, by editing the CEWP and inserting a link to your html file in the “Content Link” part of the Content Editor box and Click the “OK” or “Apply” button.
Note
You’ll require some experience with JavaScript to get through this article.
 
As far as the contents of the html file, I am not going to describe the css part of the code as it is not the scope of this article. You can take a look at that part of the file in more detail. The JavaScript part of the file is the most important. This is the part of the file that performs the magic. Within the <script> tag, at the top I declared my global variables as follows,
  1. // declare global variables  
  2.   
  3. // variables for text  
  4. var txtTypesOfEvents = "Type of Events";  
  5. var txtFestivals = "Festivals";  
  6. var txtParties = "Parties";  
  7. var txtGalas = "Galas";   
  8.   
  9. // variable for text objects  
  10. var fldLocation = {}  
  11. var fldTypesOfEvents = {}   
  12. var fldFestivals = {}   
  13. var fldParties = {}   
  14. var fldGalas = {}  
  15.   
  16. // variables for field control objects  
  17. var inputLocation = {}  
  18. var selectTypesOfEvents = {}  
  19. var selectFestivals = {}    
  20. var selectParties = {}   
  21. var selectGalas = {}  
Now, I will use the document-ready method to execute my jQuery. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready. The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. The ready() method specifies what happens when a ready event occurs. The ready() method should not be used together with <body onload="">.
  1. $(document).ready(function(){  
  2. // declare select and input objects by title  
  3. selectTypesOfEvents = $("select[title='" + txtTypesOfEvents + "']");   
  4. // select field that matches txtFestivals  
  5. selectFestivals = $("select[title='" + txtFestivals + "']");   
  6. // select field that matches txtFestivals  
  7. selectParties = $("select[title='" + txtParties + "']");   
  8. // select field that matches txtParties  
  9. inputGalas = $("input[title='" + txtGalas + "']");   
  10. // input field that matches txtGalas               
  11. // declare field control by table roll  
  12. fldTypesOfEvents = selectTypesOfEvents.closest('tr');   
  13. // roll that contains selectTypesOfEvents   
  14. fldFestivals = selectFestivals.closest('tr');   
  15. // roll that contains selectFestivals   
  16. fldParties = selectParties.closest('tr');   
  17. // roll that contains selectParties  
  18. fldGalas = inputGalas.closest('tr');   
  19. // roll that contains selectGalas  
  20. // hide dropdown fields and input fields when they are empty  
  21. if (selectFestivals.val() == "" || selectFestivals.val() == 0) {  
  22. fldFestivals.hide();    
  23. }    
  24. if (selectParties.val() == "" || selectParties.val() == 0) {  
  25. fldParties.hide();    
  26. }   
  27. if (inputGalas.val() == "") {  
  28. fldGalas.hide();    
  29. }    
  30.          
  31. // perform operations on "Types Of Events" field change  
  32.        selectTypesOfEvents.change(function() {  
  33.                   
  34.         if ($(this).val() == txtFestivals) { // change to "Festivals"  
  35.                 fldFestivals.show();  
  36.                 fldParties.hide();  
  37.              fldGalas.hide();    
  38.              }   
  39.              if ($(this).val() == txtParties) { // change to "Parties"  
  40.                 fldFestivals.hide();  
  41.              fldParties.show();  
  42.              fldGalas.hide();    
  43.              }   
  44.              if ($(this).val() == txtGalas) { // change to "Galas"  
  45.              fldFestivals.hide();  
  46.              fldParties.hide();  
  47.              fldGalas.show();     
  48.              }   
  49.   
  50. });  
  51.             // perform operations on "Festivals" field change  
  52.             selectFestivals.change(function() {   
  53.                 if ($(this).val() == "Wireless") {  
  54.                     alert("This is an outdoor event, please come early and bring your umbrella in case it rains!");   
  55.                 }   
  56.   
  57.             });  
  58.   
  59.         });  
Note
If you select Yes to “Require that this column contains information:” in the list settings, for OOTB field validation, i.e. making that field mandatory – your jQuery will not work. You will have to implement custom validation through JavaScript.
 
Implementing custom validation was more tricky than expected. I searched Google and read a few articles and blog posts, and tried a few things until I got it to work. The best way, perhaps the only way I know how to achieve custom validation using JavaScript is to make use the “PreSaveAction()” method in the form’s newform.aspx or editform.aspx form. This works on SharePoint Online, 2016, 2013.
 
In the below code, firstly I got the value of the “Title” field – by SharePoint field value id. That is the really long string of characters starting with the “#” symbol. You can find this id using your browser developer tool.
  1. // SharePoint specific "PreSaveAction" function  
  2.         function PreSaveAction() {  
  3.             console.log('PreSaveAction loaded');  
  4.   
  5.             // "Title" field value by id specifically for "newform.aspx"  
  6.             var fldTitleNew = $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl00_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').val();  
  7.             console.log('Title field on new', fldTitleNew);   
  8.   
  9.             // "Title" field value by id specifically for "editform.aspx"  
  10.             var fldTitleEdit = $('#ctl00_ctl41_g_fda4b637_35d6_4a94_b15e_205d2e23e04a_ctl00_ctl05_ctl00_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').val();  
  11.             console.log('Title field on Edit', fldTitleEdit);  
  12.   
  13.                 // Check if the "Title" field is empty in the "newform.aspx" or undifined and empty in the "editform.aspx" forms  
  14.                 if ((fldTitleNew == "") || (fldTitleEdit != undefined && fldTitleEdit == "")) {   
  15.                     alert("A value for 'Title' is required!");  
  16.                     $("p").text("A value for 'Title' is required!");   
  17.                     $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl00_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').parent().append("<p class='error-msg'>A value for 'Title' is required!</p>");  
  18.                     $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl00_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').focus();  
  19.                     console.log("A value for 'Title' is required!");         
  20.                     return false// stops DOM propagation, stop form submission   
  21.                 }    
  22.                   
  23.                 // Check if the "Types Of Events" field is empty or blank in the "newform.aspx" and "editform.aspx" forms  
  24.                 if (selectTypesOfEvents.val() == "" || selectTypesOfEvents.val() == 0) {  
  25.                     alert("A value for 'Type of Event' is required!");  
  26.                     $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl08_ctl00_ctl00_ctl05_ctl00_DropDownChoice').parent().append("<p class='error-msg'>A value for 'Type of Event' is required!</p>");  
  27.                     $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl08_ctl00_ctl00_ctl05_ctl00_DropDownChoice').focus();  
  28.                     console.log("A value for 'Type of Event' is required!");  
  29.                     return false// stops DOM propagation, stop form submission    
  30.   
  31.                     // Check if the "Types Of Events" field equals "Festivals" and field "Festivals" is empty or blank in the "newform.aspx" and "editform.aspx" forms  
  32.                     } else if (selectTypesOfEvents.val() == txtFestivals && selectFestivals.val() == "") {  
  33.                         alert("A value for 'Festivals' is required!");  
  34.   
  35.                         $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl09_ctl00_ctl00_ctl05_ctl00_DropDownChoice').parent().append("<p class='error-msg'>A value for 'Festivals' is required!</p>");  
  36.                         $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl09_ctl00_ctl00_ctl05_ctl00_DropDownChoice').focus();  
  37.                         console.log("A value for 'Festivals' is required!");   
  38.                         return false;     
  39.                           
  40.                         // Check if the "Types Of Events" field equals "Parties" and field "Parties" is empty or blank in the "newform.aspx" and "editform.aspx" forms  
  41.                         } else {   
  42.                             if (selectTypesOfEvents.val() == txtParties && selectParties.val() == "") {  
  43.                             alert("A value for 'Parties' is required!'");  
  44.                             $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl10_ctl00_ctl00_ctl05_ctl00_DropDownChoice').parent().append("<p class='error-msg'>A value for 'Parties' is required!</p>");  
  45.                             $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl10_ctl00_ctl00_ctl05_ctl00_DropDownChoice').focus();  
  46.                             console.log("A value for 'Parties' is required!");  
  47.                             return false;   
  48.                               
  49.                             // Check if the "Types Of Events" field equals "Galas" and field "Galas" is empty or blank in the "newform.aspx" and "editform.aspx" forms  
  50.                             } else if (selectTypesOfEvents.val() == txtGalas && inputGalas.val() == "") {  
  51.                                 alert("A value for 'Galas' is required!");    
  52.                                 $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl11_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').parent().append("<p class='error-msg'>A value for 'Galas' is required!</p>");  
  53.                                 $('#ctl00_ctl41_g_98d75819_9fcb_451b_87d4_c513b39997e4_ctl00_ctl05_ctl11_ctl00_ctl00_ctl05_ctl00_ctl00_TextField').focus();  
  54.                                 console.log("A value for 'Galas' is required!");  
  55.                                 return false;   
  56.                             }     
  57.                         }      
  58.   
  59.                 return true;  
  60.         }    
In the above code, I’ve commented the code to explain what is going on. As you can see, I am using both an alert and text on the page to warn the user but both aren’t necessary. My preference is using just text (which fade out). When the user Click the “Save” button, and any of the fields are blank, the user will be alerted as shown in the below images.
 
How To Apply Custom Validation On A SharePoint Form (New And Edit)
Figure 1: Validate “Title” field – warning text appended to it
 
How To Apply Custom Validation On A SharePoint Form (New And Edit) 
Figure 2: Validate “Festivals” field – warning text appended to it and alert text