Sunday, September 3, 2017

Validation Of Duplicate and Empty Rows in JavaScript

Hi there!

In this blog post you will learn how to avoid (validate) duplication and empty rows in a table when you search and select data from a drop down list.

 So every time when I want to implement this validation at my work place I use a common function to identify the id of the selected data (object) from the drop down list and the id of already stored objects and if they are matching or equal, the function will return true hence not allowing duplicate rows. Below is the common function to avoid duplicate rows.

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return true;
        }
    }
    return false;
}


Paste the above function somewhere in your controller and call it in the function used to add data to the table. For an example, suppose you want to add user details to a table and you have a function called "AddUserDetails".

$scope.AddUserDetails = function () {

         var tempList = { } ; 
     
         tempList.id = $scope.selectedUserDetails.id;

         templist.name= $scope.selectedUserDetails.name;

         if ( !containsObject (tempList , storedUserList )

         {
             $scope.storedUserList.push ( tempList ) ;
         }
}


The newly selected object is passed to an array called "tempList" and that object in tempList is checked with every object that is stored in the "storedUserList" array by the common function. If there are matching id's of objects in those two arrays, the function will not push the selected object to the storedUserList array.

----- Happy Coding! -----





No comments:

Post a Comment