Tuesday, July 8, 2014

Form / Data Validation Using jQuery & Javascript

Hello Readers,

It has been a while since my last post and I apologize for the delay!  Today I wanted to talk about how to use jQuery and JavaScript to validate field values in SP forms.  This example will be extremely simple, but hopefully it will help cover the basics, as well as spark some ideas on how you might want to validate entries on your forms.  You will need to add this script to the new & display form.aspx pages with either with a content editor or script editor web part.

If you are just getting started with JavaScript and jQuery I would highly recommend reading through Mark  Rackley’s  A Dummies Guide to SharePoint and jQuery-Getting & Setting SharePoint Form Fields which is a fantastic blog series as well as Marc Anderson’s  Blog which is loaded with great content.  Both of their sites run through all of the selectors i.e. when to use select, input, etc. so I will not be covering that in this post.

For my example today I have a simple custom list with the following fields:
            Title: (single line of text) (input field)
            Candidate Hired: (combo box dropdown N/A, No, Yes) (select field)
            Candidate Start Date: (date & time control)

I want to an alert to pop up letting the user know that they accidentally left the Start Date blank when Candidate Hired = “Yes” & the Candidate Start Date was left blank.  If we were going to rely on this script for validation we would want to put in other conditions to handle scenarios such as having a start date without selecting yes, but for the sake of simplicity we will keep it very basic.

To Do This We Will Need:
·         A reference to the jQuery library
o   We can reference the library either with a CDN (content delivery network) or by downloading the library and storing it somewhere on our SharePoint site and linking to it there.
o   If you download the library I would recommend saving the file with a title of jQuery and adding an additional field to the library with the version number.  This is a good practice since if you have multiple scripts linked to the jQuery library, they won’t break when a new version is uploaded and the file name changes.
·         This Script
<script type="text/javascript" src="LINK TO jQuery Location"></script>
 <script type="text/javascript" language="javascript">
 function PreSaveAction() {
drop = $("select[title='Candidate Hired']").val();
date = $("input[title='Candidate Start Date']").val();
    if (drop ==="Yes" && date===""){
        alert("You Shall Not Pass, Fix The Date!");
        return false;
    }   
        return true;
}
 </script>

How Does The Script Work?
Essentially what this script does is to check to make sure that the Candidate Start Date is not left blank if the user indicated they were hired before they can save the form.  We are obtaining the values based on the form’s display names **Not Internal Names!!** and then checking those values before the form can be saved.  If the form matches our criteria of Hired = yes & Start Date = “”, then our script will pull a Galdalf when the user tries to submit the item with a “YOU SHALL NOT PASS” until the form has been fixed.  

In order to repurpose the script you could swap out the display names and use it as is or you could use it as a template to start writing your own validation scripts.  Although some validation can be done via the column validation and list validation in SharePoint, I always run into scenarios where a simple script enhances the user’s experience as well as ensures the inputted data is correct.  An example of this would be to use JavaScript to create an input mask for form fields or to ensure that an email address field actually contains @ & .com.

Well again this script is super basic, but I hope that this sparks some thoughts on where your forms could be enhanced and how you can use jQuery and JavaScript to get it done!


Best Regards,
Dan

4 comments:

  1. Alright! Thanks for sharing these ideas. I've learned a lot about this.

    ReplyDelete
  2. Hi Dan,

    Thank you a lot for this .

    However, it seems not to work to me. I place the query within content editor boxes in both New Form and Display Form aspx pages of the List.

    The alert does not fire when I hit Save button. What could be the problem?

    Appreciate it,

    Ged

    ReplyDelete
    Replies
    1. Hi Gediminas, sorry for the late response. I think the first thing I would ensure is that jQuery is indeed loaded. To do this I would navigate to new and edit forms and open your browser's developer tools (F12 key). Next navigate to the console area and try $(document).ready(function(){alert('jquery available')}); If you receive a message such as "$ is not defined" or "jQuery is not defined" you probably have a bad reference to the jQuery library. If these do fire you know that jQuery is loaded and that the issue is with your script. I would also ensure that you are targeting the correct fields. If you are still having an issue maybe you can send me your code and I can try and help troubleshoot? Best Regards, Dan

      Delete
  3. This comment has been removed by the author.

    ReplyDelete