Friday, April 8, 2011

jQuery - Using jQuery to attach regular expression validation(no special character to be added in Title field) to a SharePoint list form field

Write the below code on the New Form of the SharePoint list.

<script type='type/javascript'>
  
  _spBodyOnLoadFunctionNames.push("attachToTitleField");
  
  function attachToTitleField() {
   var titleField = $('input[title=Title]'); //Find title field on the form
   
   //Add a DIV element to provide a place for an error message from the RegEx validation
   titleField.parent().append("<div id='GilesH_titleValidation'></div>");
  
  //Use jQuery to attach the validateAlphanumeric function on keyup
  titleField.keyup(function() {
   validateAlphanumeric(titleField.val());
  });
 }

 function validateAlphanumeric(stringValue) {
  
  //Allows alphanumeric only for the 1st character
  //after the 2nd character, alphanumeric and spaces allowed upto 255 characters
  var regExpressionValue = /^[0-9A-Za-z][0-9A-Za-z\s]{0,255}$/; 
  var re = new RegExp(regExpressionValue);
   
  if (stringValue.match(re)) {
   //alert("Successful match"); //Debug
   
   //Allow Save
   $('a[id=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:inline-block;"); //Show Ribbon Save Button
   $('input[id*=SaveItem]').attr("disabled",""); //Re-enable Form Save Button
   
   //Blank Error Message
   $('div[id*=GilesH_titleValidation]').text(""); //Blank custom error message
  } else {
   //alert("No match"); //Debug
   
   //Stop Save
   $('a[id*=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:none;"); //Hide Ribbon Save Button
   $('input[id*=SaveItem]').attr("disabled","true"); //Disable Form Save Button
   
   //Provide Error Message
   $('div[id*=GilesH_titleValidation]').text("The title you have entered is invalid. Only alphanumeric characters and spaces are allowed.");
  }
 }

 </script>


N.B: Add an extra <DIV> element next to the Title field to notify the user of what is going on.

No comments:

Post a Comment