1

I am validating sharepoint list fields on PreSaveAction method of sharepoint list new form. I have done some customization and have put some labels with error messages under the sharepoint formfields. What should I do, any help would be appreciated.Below is my "New Form" code,

<script type="text/javascript">

    var managerName;
    var flg;
    var managerLogId;
    var managerEmailId;
    var managerGUID;
    var vpName;
    var vpLoginId;
    var vpEmailId;
    var vpGUID;
    var technology;
    var projectStartDate;
    var projectEndDate;
    var clientContext;
    var startDatevalid = true;
    var endDatevalid = true;

    jQuery(document).ready(function()    
    {    
        //Set the Field to Read only and change its background colour    
        jQuery("input[title='TechnologiesIds']").attr("readonly","true").css('background-color','#F6F6F6');    

    });     

     function PreSaveAction()
     {
            // event.preventDefault();
        flg = 0;
        managerName = jQuery("input[title='ProjectManagerName']").val();    
        managerLogId = jQuery("input[title='ManagerLoginId']").val();   
        managerEmailId = jQuery("input[title='ManagerEmailId']").val();
        managerGUID = jQuery("input[title='ManagerGUID']").val();       

        vpName = jQuery("input[title='VPName']").val();
        vpLoginId = jQuery("input[title='VPLoginId']").val();
        vpEmailId = jQuery("input[title='VPEmailId']").val();
        vpGUID = jQuery("input[title='VPGUID']").val();


         var s = '';
         var cnt = 0;

        jQuery("#ctl00_ctl40_g_d08ffacb_a2dd_40a6_bde0_9f4991a04c0f_ff271_ctl00_ctl00_SelectResult option").each(function()
        {

            if(cnt == 1)
                s = s + " , " + jQuery(this).attr('value');
            else
                s = jQuery(this).attr('value');

            cnt = 1;

        });


        technology = s;

        jQuery("input[title='TechnologiesIds']").val(technology);



        projectStartDate = jQuery("input[title='ProjectStartDate']").val();
        projectEndDate = jQuery("input[title='ProjectEndDate']").val();

        if(projectStartDate != "" && projectEndDate != "")
        {
            startDatevalid = isDate(projectStartDate);
            endDatevalid = isDate(projectEndDate);
        }

        validateEmp();



           if(flg==1)
           {
                return false;
           }
           else
           {
                jQuery("#labelProjectManager").html("");                        
                jQuery("#labelManagerLogin").html("");          
                jQuery("#labelManagerEmail").html("");      
                jQuery("#labelManagerGUID").html("");   
                jQuery("#labelVPName").html(""); 
                jQuery("#labelVPLogin").html("");       
                jQuery("#labelVPEmail").html("");       
                jQuery("#labelVPGUID").html("");        
                return true;
           }    


     //     return true;

     }


     function validateEmp()
     {

            clientContext = SP.ClientContext.get_current();     
            var list = clientContext.get_web().get_lists().getByTitle('Profile');

            //********************************Code for Manager Validation************************************//     

            var mgrcamlQuery = new SP.CamlQuery();

        /*  mgrcamlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='FullName' /><Value Type='Text'>"
                                +managerName+"</Value></Eq><And><Eq><FieldRef Name='LoginName' /><Value Type='Text'>"
                                +managerLogId+"</Value></Eq><And><Eq><FieldRef Name='EmailID' /><Value Type='Text'>"
                                +managerEmailId+"</Value></Eq><Eq><FieldRef Name='EmployeeGuid' /><Value Type='Text'>"
                                +managerGUID+"</Value></Eq></And></And></And></Where></Query></View>");     */

            mgrcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FullName' /><Value Type='Text'>"+managerName+"</Value></Eq></Where></Query></View>");
            this.mgrcollListItem = list.getItems(mgrcamlQuery);
            mgrcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='LoginName' /><Value Type='Text'>"+managerLogId+"</Value></Eq></Where></Query></View>");
            this.mgrlogitem = list.getItems(mgrcamlQuery);
            mgrcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='EmailID' /><Value Type='Text'>"+managerEmailId+"</Value></Eq></Where></Query></View>");
            this.mgrEmailitem = list.getItems(mgrcamlQuery);
            mgrcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='EmployeeGuid' /><Value Type='Text'>"+managerGUID+"</Value></Eq></Where></Query></View>");
            this.mgrGUIDitem = list.getItems(mgrcamlQuery);


            //***********************************Code for VP Validation**************************************//

            var vpcamlQuery = new SP.CamlQuery();

        /*  vpcamlQuery.set_viewXml("<View><Query><Where><And><Eq><FieldRef Name='FullName' /><Value Type='Text'>"
                                +vpName+"</Value></Eq><And><Eq><FieldRef Name='LoginName' /><Value Type='Text'>"
                                +vpLoginId+"</Value></Eq><And><Eq><FieldRef Name='EmailID' /><Value Type='Text'>"
                                +vpEmailId+"</Value></Eq><Eq><FieldRef Name='EmployeeGuid' /><Value Type='Text'>"
                                +vpGUID+"</Value></Eq></And></And></And></Where></Query></View>");      */

            vpcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='FullName' /><Value Type='Text'>"+vpName+"</Value></Eq></Where></Query></View>");
            this.vpcollListItem = list.getItems(vpcamlQuery);
            vpcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='LoginName' /><Value Type='Text'>"+vpLoginId+"</Value></Eq></Where></Query></View>");
            this.vplogitem = list.getItems(vpcamlQuery);
            vpcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='EmailID' /><Value Type='Text'>"+vpEmailId+"</Value></Eq></Where></Query></View>");
            this.vpEmailitem = list.getItems(vpcamlQuery);
            vpcamlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='EmployeeGuid' /><Value Type='Text'>"+vpGUID+"</Value></Eq></Where></Query></View>");
            this.vpGUIDitem = list.getItems(vpcamlQuery);


        //  alert("MngrName: "+managerName +"MngrLogin: "+managerLogId +"MngrEmail: "+managerEmailId +"MngrGUID: "+managerGUID +"VPName: "+vpName +"VPLoginID: "+vpLoginId+"VPEmailID: "+vpEmailId+"VPGUID: "+vpGUID+"Technology: "+technology+"StartDate: "+projectStartDate+"EndDate: "+projectEndDate);

            clientContext.load(mgrcollListItem);
            clientContext.load(mgrlogitem);
            clientContext.load(mgrEmailitem);
            clientContext.load(mgrGUIDitem);

            clientContext.load(vpcollListItem);
            clientContext.load(vplogitem);
            clientContext.load(vpEmailitem);
            clientContext.load(vpGUIDitem); 

            clientContext.executeQueryAsync(Function.createDelegate(this, this.onValidateEmpSucceeded), Function.createDelegate(this, this.onValidateEmpFailed));        

     }

     function onValidateEmpSucceeded(sender, args)
     {

            flg=0;
        //  alert("Succeeded: "+mgrcollListItem.get_count()+"VpCount: "+vpcollListItem.get_count());


            if(mgrcollListItem.get_count() == 0 && managerName != "")
            {
                flg = 1;
                alert(""+flg);
                //jQuery("#labelProjectManager").html("Invalid name. User does not exist.");    
                jQuery("#labelProjectManager").css("display", "block");
                alert("Invalid");
                return false;
            }
            else
            {
                //jQuery("#labelProjectManager").html("");  
                jQuery("#labelProjectManager").css("display", "none");              
            }
            if(mgrlogitem.get_count() == 0 && managerLogId != "")
            {
                flg = 1;
                //jQuery("#labelManagerLogin").html("Invalid loginname. User does not exist."); 
                alert("Manager Login  "+mgrlogitem.get_count());                
            }
            else
            {
                //jQuery("#labelManagerLogin").html("");    
                alert("Manager Login  "+mgrlogitem.get_count());    
            }

            if(mgrEmailitem.get_count() == 0 && managerEmailId != "")
            {
                flg = 1;
                //jQuery("#labelManagerEmail").html("Invalid email id. User does not exist.");          
            }
            else
            {
                //jQuery("#labelManagerEmail").html("");
            }

            if(mgrGUIDitem.get_count() == 0 && managerGUID != "")
            {
                flg = 1;
                //jQuery("#labelManagerGUID").html("Invalid guid. User does not exist.");           
            }
            else
            {
                //jQuery("#labelManagerGUID").html("");
            }

            if(vpcollListItem.get_count() == 0 && vpName != "")
            {
                flg = 1;
                //jQuery("#labelVPName").html("Invalid name. User does not exist.");            
            }
            else
            {
                //jQuery("#labelVPName").html("");
            }

            if(vplogitem.get_count() == 0 && vpLoginId != "")
            {
                flg = 1;
                //jQuery("#labelVPLogin").html("Invalid loginname. User does not exist.");          
            }
            else
            {
                //jQuery("#labelVPLogin").html("");
            }

            if(vpEmailitem.get_count() == 0 && vpEmailId != "")
            {
                flg = 1;
                //jQuery("#labelVPEmail").html("Invalid email id. User does not exist.");           
            }
            else
            {
                //jQuery("#labelVPEmail").html("");
            }

            if(vpGUIDitem.get_count() == 0 && vpGUID != "")
            {
                flg = 1;
                //jQuery("#labelVPGUID").html("Invalid guid. User does not exist.");            
            }
            else
            {
                //jQuery("#labelVPGUID").html("");
            }           


            if(startDatevalid == "false")
            {
                flg = 1;
                //jQuery("#labelStartDate").html("Invalid date. Please enter appropriate date.");   
                alert(" "+startDatevalid);      
            }
            else
            {
                //jQuery("#labelStartDate").html("");
            }

            if(endDatevalid == false)
            {
                flg = 1;
                //jQuery("#labelEndDate").html("Invalid date. Please enter appropriate date.");             
            }
            else
            {
                //jQuery("#labelEndDate").html("");
            }

            if(startDatevalid == true && endDatevalid == true)
            {

                var projStart = new Date(projectStartDate);
                var projEnd = new Date(projectEndDate);

                var startDate = projStart.getDate() + "/" + projStart.getMonth() + "/" + projStart.getFullYear();
                var endDate = projEnd.getDate() + "/" + projEnd.getMonth() + "/" + projEnd.getFullYear();

            //  alert("Start: "+projStart+"End: "+projEnd);

                if(projStart > projEnd)
                {

                    flg = 1;
                    //jQuery("#labelDateValid").html("Start date should be smaller than end date.");
                    alert("Start: "+ projStart.getFullYear() +"End: " + projEnd.getFullYear());

                }
                else
                {
                    ///jQuery("#labelDateValid").html("");

                }
            }



                if(managerName == "")
                {
                    flg = 1;
                    //jQuery("#labelProjectManager").html("You must specify a value for this required field.");                         
                }
                if(managerLogId == "")
                {           
                    flg = 1;                        
                    //jQuery("#labelManagerLogin").html("You must specify a value for this required field.");           

                }
                if(managerEmailId == "")
                {
                    flg = 1;
                    //jQuery("#labelManagerEmail").html("You must specify a value for this required field.");       

                }
                if(managerGUID == "")
                {
                    flg = 1;
                    //jQuery("#labelManagerGUID").html("You must specify a value for this required field.");
                }
                if(vpName == "")
                {           
                    flg = 1;
                    ///jQuery("#labelVPName").html("You must specify a value for this required field.");                
                }
                if(vpLoginId == "")
                {       
                    flg = 1;
                    //jQuery("#labelVPLogin").html("You must specify a value for this required field.");        

                }
                if(vpEmailId == "")
                {   
                    flg = 1;
                    //jQuery("#labelVPEmail").html("You must specify a value for this required field.");        

                }
                if(vpGUID == "")
                {
                    flg = 1;
                    //jQuery("#labelVPGUID").html("You must specify a value for this required field.");         
                }
                if(projectStartDate == "")
                {
                    flg = 1;
                    //jQuery("#labelStartDate").html("You must specify a value for this required field.");      
                }
                if(projectEndDate == "")
                {
                    flg = 1;
                    //jQuery("#labelEndDate").html("You must specify a value for this required field.");        
                }



     }

     function onValidateEmpFailed(sender, args)
     { 
         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }


    function isDate(txtDate)
    {
        var currVal = txtDate;
        if(currVal == '')
            return false;

        var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;

        //Declare Regex
        var dtArray = currVal.match(rxDatePattern); // is format OK?

        if (dtArray == null) 
            return false;

        //Checks for dd/mm/yyyy format.

        dtMonth = dtArray[3];
        dtDay= dtArray[1];
        dtYear = dtArray[5];    

        if (dtMonth < 1 || dtMonth > 12) 
            return false;
        else if (dtDay < 1 || dtDay> 31) 
            return false;
        else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
            return false;
        else if (dtMonth == 2) 
        {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
            if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                    return false;
        }
        return true;
    }



</script>
  • Where are you calling PreSaveAction method ? – Yayati Aug 4 '15 at 11:05
  • we don't need to call PreSaveAction method. It is called by sharepoint on submit button click of sharepoint new form – Niranjan Kulkarni Aug 4 '15 at 11:15
  • In PreSaveAction method, you are calling validateEmp method which contains executeQueryAsync method. So it might be the reason that before onValidateEmpSucceeded method completes, the PreSaveAction method returns true and no validation messages are shown. – Yayati Aug 4 '15 at 11:37
  • But the same code was working yesterday & showing error messages, and today it is giving me the issue, and all my validations are working right, I am only having the issue with error messages as they are not shown when the wrong data is entered – Niranjan Kulkarni Aug 4 '15 at 12:19
  • Have a look at jQuery Deferred to wait for callback. As @yayati stated, PreSaveAction will not wait for your asynch call – JayHell Aug 4 '15 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.