Tuesday 9 April 2013

Sharepoint 2013 Apps - Custom validation in default NewForm and EditForm pages of Sharepoint lists

Many times we come across scenarios where we need to perform some custom validations in NewForm and EditForm pages of a Sharepoint list. We want custom validation rules be checked against the form fields before the item is saved or we just want to pre-fill some form fields before the item is saved.

Sharepoint list doesn't provide any default mechanism to achieve such functionality except creating totally customized NewFrom and EditForm pages for the list.

Luckily there is one quick and fully supported way out to this problem, i.e. using JavaScript.

Lets get into a bit detail and see what we need to do in order to add our custom validation rules using JavaScript.

Following is the code snippet from the onclick attribute of the "Save" button in a custom Sharepoint list EditForm or NewForm page.

     if (!PreSaveItem())
          return false;
     if (SPClientForms.ClientFormManager.SubmitClientForm('WPQ1'))
          return false;
     .
     .


When the "Save" button is pressed a function "PreSaveItem" is executed first. If the function returns false no further action takes place and the execution stops immediately.

Now lets check out the implementation of the function "PreSaveItem" which is defined in form.js. Following is the definition of "PreSaveItem" function:

     function PreSaveItem(){
          a:;
          return "function" == typeof PreSaveAction?PreSaveAction():true
     }


The function "PreSaveItem" is simply checking if a function with name "PreSaveAction" exists or not and if it exists invoke it and return its returned value (true/false) or return "true" by default if no functions exists with this name.

At this point we know that if we can somehow define this function in NewForm and EditForm pages it will be called when "Save" button will be pressed and we can write all our custom validation logic within this function which will return either true/false to let NewForm and EditForm pages know if it should save the item or not.

Lets check out how we can define this function in NewForm and EditForm pages.

First add a new JavaScript file. You can name it anything. In my example i added JavaScript file with name "PreSaveAction.js" in Scripts folder.

In Elements.xml file of the list find the tag List/MetaData/Forms
Find the two "Form" tags with Type "EditForm" and "NewForm"
Add a new attribute "JSLink" to include JavaScript file in both of these pages.


Please note that multiple JS files can be included in NewForm and EditForm pages using the same approach. In this case multiple JS files can be specified in "JSLink" attribute separated by a pipe "|" sign. In the following image i have also included jQuery so that i could easily reference the required form field using jQuery selectors.




Next we need to add the function "PreSaveAction" in the JavaScript file we added in previous steps and specify our custom validation rules in it.

For the sake of simplicity, in the following code snippet i am checking if the title is equal to "hannan", only then it should save the item else an alert box is shown telling the user what value is expected in the "Title" field.

     function PreSaveAction() {
         var title = $("input[title='Title']").val();

         if (title == "hannan")
             return true;
         else {
             alert("Title should be equal to: hannan");
             return false;
         }
     }


One important thing to note here is how i referenced the "Title" form field using jQuery's attribute selector. You can reference other form fields (if any) using this approach. For that you will need to specify the correct value of title attribute for those form fields. In order to find out the value of title attribute for forms fields check out the "Name" attribute of "Field" tag in List/MetaData/Fields in Schema.xml file of the list. Alternatively you can also reference the form fields using IDs if exact client IDs are known.

4 comments:

  1. How to transform the edit form using jquery? How to embed the js file in edit form so controls can be changed or manipulated.

    ReplyDelete
    Replies
    1. You can include jquery in EditForm or NewForm by specifying its path in JSLink attribute.
      Please see the example above where two javascript files are specified in JSLink attribute separated by a pipe sign (|).
      Please make appropriate modification to the jquery js file path as required.

      Delete
  2. Can you put the error message in-line on the page?

    ReplyDelete
  3. Hello Hannan

    I had this issue coming up on click of save button. It saves all fied values except attachements.

    input type='button' value='Save' onclick=\"SPClientForms.ClientFormManager.SubmitClientForm('{{FormId}}')\" style='margin-left:0' >


    Am i doing anything wrong? or how do we even save attachements during save button click.

    Waiting for earliest response.

    BR
    Shiva Kumar Soma

    ReplyDelete