Validation on SharePoint Forms – Part Four

Trolling the MSDN SharePoint – Design and Customization forum is proving to be a great learning experience all around.  I see questions I can’t answer which cause me to research them, and hopefully, I’m providing some answers which help others.

One of the things I saw over the last few days was a link to a post which explained how to use the PreSaveAction() JavaScript function to validate form data before it is saved.  (Check out my recent previous posts about validation in SharePoint forms: Parts One, Two, and Three.  I’ve posted about many other bits and pieces of this over time as well.)  Greg Osimowicz explains this in a post entitled SharePoint Forms date validation using JavaScript with reference to Edin Kapić‘s post entitled Add JavaScript Date Validation into List Item forms.  Read through both posts if you want to see how this holds together.

The cool thing is that there is a JavaScript function called PreSaveAction() which is called by FORMS.JS if it is defined in the form (NewForm.aspx or EditForm.aspx).  I had always converted the default List Form Web Part (LFWP) on forms to a Data View Web Part (DVWP) in order to “hook in” my JavaScript into the submit button for validation but it turns out that you don’t necessarily need to do that if you use the PreSaveAction function instead.

So, for example, if you want to validate that a Start Date is before an End Date (as shown in the posts above), you’d add this JavaScript to your page:

<script language="javascript" type="text/javascript">
function PreSaveAction() {
    var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Start Time");
    var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","End Time");
    var arrDate1 = date1.value.split("/");
    var useDate1 = new Date(arrDate1[2], arrDate1[0]-1, arrDate1[1]);
    var arrDate2 = date2.value.split("/");
    var useDate2 = new Date(arrDate2[2], arrDate2[0]-1, arrDate2[1]);
    if(useDate1 > useDate2)
    {
        alert("The End Date cannot happen earlier than the Start Date");
        return false; // Cancel the item save process
    }
    return true; // OK to proceed with the save item
}

// getTagFromIdentifierAndTitle: Find a form field object using its tagName, identifier, and title to find it in the page
// Arguments:
//                            tagName:            The type of input field (input, select, etc.)
//                            identifier:            The identifier for the instance of the fieldName (ff1, ff2, etc.)
//                            title:                       The title of the list column
//
function getTagFromIdentifierAndTitle(tagName, identifier, title) {
    var len = identifier.length;
    var tags = document.getElementsByTagName(tagName);

    for (var i=0; i < tags.length; i++) {
        var tempString = tags[i].id;
        if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
            return tags[i];
        }
    }
    return null;
}

</script>

Similar Posts

64 Comments

  1. Hi Marc,
    Thanks for the post.I have tried your code which is working fine in newform.aspx but in editform.aspx it is validating th form even when start date is less or greater than due date. if I enter both the days equal then it is saying nothing. Do I need to change anything for editform.aspx?

      1. Hi Marc,
        Sorry for my late reply I am even working on other projects also in parallel and this task is not yet done yet. My issue is when I write multiple If conditions(not nested If’s)I am getting the output only for the condition which is just above the return true; statement and for all other If’s its not showing up..

        Regards,
        Harish

        1. Harish:

          It’s a little hard for me to know what’s happening without seeing your code, but a couple of thoughts:
          * If you have multiple IFs, you won’t want to do a return until all of them have executed. You’ll probably want to have a variable which you can set to false and then eventually return it.
          * Nested if-else-if-else is probably what you want to do and then if any one of your conditions fails, you would return false.

          If you want to send me your scripts, I’d be happy to take a look. You can’t paste script into comments, but you can use the Contact tab above.

          M.

  2. Thanks for the great post Marc. I got it. Apart from date time fields I also used drop down and boolean fields for my validation with reference to your code.
    I am trying to paste my code here so that it may help some one as an another example but it is saying discarded when I say submit.

  3. Thanks for the great post and your quick reply Marc.I got it. Apart from date time fields I also used drop down and boolean fields for my validation with reference to your code.
    I am trying to paste my code here so that it may help some one as an another example but it is saying discarded when I say submit.

  4. Hi Marc,
    I Just want to confirm whether you got my code which I emailed you using contact link above, that code is not giving perfect validations even though its working can you please check it and let me know what’s wrong in that code.

    Regards,
    Harish

      1. On September 16th I did a copy paste of the script I am using in to the ‘contact’ mwnu option mail id provided above. I will again post my script to you now.

  5. Hey Marc,

    Any thoughts on using jQuery to do all the selection for you? Seems your validation code does a lot of DOM traversal which jQuery is great for. Understandably you’re adding jQuery to the mix rather than straight JavaScript but I thought I would ask why you didn’t go down that path.

    Thanks!

    1. Bil:

      Simple answer on this one: check the date. I hadn’t even touched jQuery at that point.

      However, I’ve been wondering whether my tips ‘n such going forward should be too jQuery-skewed. I would hazard to guess that more people out there know JavaScript and are cautious about jumping onto the jQuery bandwagon, regardless of the benefits.

      Another thing I’ve considered is doing a sort of jQuery round-up of a lot of my old posts to “translate” them into jQuery to both give the [better] code and raise interest in jQuery itself.

      And finally, I’m slowly building some of the posts that people have hit the most over tiem into functions in my jQuery Library for SharePoint Web Services.

      M.

  6. HI Marc
    Nice Post.but i have sharepoint:Controls which bound to Sql Server Datasource.
    your post is for Newitemform for list how can i use javascript to validate sharepoint:Controls .
    well i can use Vlidation Control but these control dont work for Date type

    can you please guide me on this ?

    1. The JavaScript method ought to work regardless of the control type because it’s working based on the values contained in the DOM. The PreSaveAction processing occurs client-side, so all you nned to do is build the right logic into your script.

      M.

  7. hi Marc..

    i tried this code and it is working fine, but when today i tried to put the start date = 11/25/2009 and end date = 12/2/2009 the code gave me that the end date is less than the start date which is not correct … is this code related to a spacific date format dd/mm/yyyy and if so how can we change it to mm/dd/yyyy

    thank you

    1. The example I give is based on the date format being in en-US (1033) locale format, meaning MM/DD/YYYY. The JavaScript breaks the date apart and formats it as YYYYMMDD for comparison purposes. If you have a different locale format, you’ll need to adjust the JavaScript accordingly.

      M.

  8. Hi Marc,
    I have been using this code but I am also getting same error as Tia. All dateandtime columns are like mm/dd/yyyy format only but for some dates this javascript for me also showing up incorrect validations.
    if startdate=11/30/2009 and enddate=12/1/2009 it is saying end date cannot happen earlier than start date.Same error even if startdate=11/30/2009 and enddate=1/1/2010.

    Regards,
    Harish

    1. Harish and Tia:

      My bad. I just tested this out in a form in my dev environment, and there was indeed an issue. I had mixed some code from an environment which had used European date formats (DD/MM/YYYY) with a US-based example (MM/DD/YYYY). I just updated the script above to work for US-formatted dates.

      Keep in mind that in many cases, I’m posting my code just as an example. It may or may not be exactly what you are looking for, and some debugging is *always* a good idea on your end to be sure it’s doing what *you* wanted, not what I originally may have intended.

      Also, jQuery makes this type of thing *much* easier when it comes to selectors, so if you’re already riding the jQuery train, I’d suggest you use it instead.

      M.

  9. Hi Marc,
    Thank you. This modified code is working perfectly. sorry I should have tried this before giving a comment here.
    Note: In this modified code there are two if loops.I hope you remove that before someone comment that.

    thank you.

    regards,
    Harish

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.