Wednesday, February 29, 2012

Article 6: How to validate duplicate key and require value using javascript and SPServices


Step 1: Download 2 file javascript at here
jquery-1.4.2.js //Use Jquery library
jquery.SPServices-0.5.6.js//Use Webservices
Step 2: Go to Top level site | On home page | Click to Shared Documents | Upload 2 file jquery-1.4.2.js and jquery.SPServices-0.5.6.js
Step 3: Create new list name Employees
Change Title to EmployeeID //Similar Primary key but don’t set Unique
Create Fields as follows: FirstName (Single line of text), LastName (Single line of text), FullName (Calculated (calculation based on FirstName and LastName columns))
Step 4: Go to NewForm.aspx
Step 5: Add Content Editor Webpart
Step 6: Open HTML Source
Step 7: Copy code and paste to here
<script src="../../Shared Documents/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="../../Shared Documents/jquery.SPServices-0.5.6.js" type="text/javascript"></script>
    <script>   
var isSave=true;       
//use Chrome to get ID of Title Control from client
        vartxtTitle="#ctl00_m_g_091a1007_03bb_42bf_8842_9a04d3694c48_ctl00_ctl05_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField";
        //Event Default of sharepoint "PreSaveAction"
        function PreSaveAction() {
        if ($(txtTitle).attr("value"!= "") {
            isSave true;
            $().SPServices({
                operation"GetListItems",//Default
                asyncfalse,//Default
                listName"Employees",//Your List
                completefuncfunction (xDataStatus) {//Default
                    //Loop via all item
                    $(xData.responseXML).find("z\\:row").each(function () {
                        //Get value from List and compare with input value
                        if ($(txtTitle).attr("value"== $(this).attr("ows_Title")) {
                            isSave false;
                        }
                    });
                }
            });
            //If valid
            if (isSave == true) {
                return true;
            }
            else {
                alert("Duplicate ...! Please Enter ... again");
                return false;
            }
        }
        else {
            alert("Please Enter ...");
            return false;
        }
    }
</script>
Step 8: Change something for appropriate with your structure
-          Change ID of Title Field by: Open chrome and Open NewForm.aspx page
-          Right click to TextBox EmployeeID then click Inspect element
-          Copy Id and replace your txtTitle
-          ctl00_m_g_091a1007_03bb_42bf_8842_9a04d3694c48_ctl00_ctl05_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField
Step 9: Add new item which it is duplicate with item in list and see messagebox as follows
Try Input data again with different EmployeeID
Result as follow:

0 comments:

Post a Comment