Friday, April 16, 2021

Using PreSaveItem to add custom validation to SharePoint list form

 

In this article I explain how to change the standard server side to a custom client side form validation. You can’t really change for server to client side, but you can validate your input with JavaScript before to send them to the server and then “skip” server side validation. You can do all of this by using a standard JavaScript function used on every submit button, PreSaveItem.

Out-of-the-box PreSaveItem doesn’t do anything, but on every form save action, SharePoint checks if PreSaveItems return false. In this case it doesn’t allow the form submit. See the following row to better understand what I mean.

if (!PreSaveItem()) return false;​

In a custom javascript file you have to redefine the PreSaveItem function, adding your custom data validation. In my article I wrote a function that leverage the power of regular expressions to validate an email address field. Let’s see the example below.

function PreSaveItem(){
  var err = false;
  var email = $("input[title='E-mail']");
  
  var re_email = /^[0-9a-zA-Z]+([0-9a-zA-Z]*[-._+])*[0-9a-zA-Z]+@[0-9a-zA-Z]+([-.][0-9a-zA-Z]+)*([0-9a-zA-Z]*[.])[a-zA-Z]{2,6}$​/;
  
  if (!(re_email.test(email.val())) || email.val().length == 0){
    var erremail = '<div class="ms-formvalidation"><span role="alert"><b>E-mail address</b> field is not valid.</span></div>';
    email.after(erremail);
    email.focus();
    err = true;
  }

  return !(err)

I used jQuery to select the field and to add an error message after the input when needed. I also added another little piece of  code to clear the error message when the user change the fields value.

$(document).ready(function(){
  $("input[title='E-mail']").change(function(){
    $(this).next().hide();
  }); 
});

No comments:

Post a Comment

Server Error in '/' Application when activating "Nintex Forms" web app feature.

Apparently "INSTALL-NFService" need to be run in SharePoint PowerShell to fix this problem.   When I installed Nintex Forms agai...