티스토리 뷰

Last time, we went on a deep dive into importing CSV files, mapping the fields, and storing that data using AngularJS's `$http.post`. If you missed that part, make sure to catch up here . Today, as promised, we'll focus on a critical aspect of any data manipulation process: validation.

 


Why Data Validation is Important

First things first: Why do we even need to validate data? Simply put, garbage in equals garbage out. If you start with inaccurate or incomplete data, no amount of fancy algorithms or complex systems can make your application function correctly. Validation ensures that the data being sent to your API meets certain criteria, reducing the likelihood of errors and ensuring integrity.


Implementing Basic Validation Logic

Before you hit the "Save" button and make the POST request to the API, you should make sure that the data is valid. Let's start by adding some basic checks in our controller.

Here's an updated `$scope.validateData` function:

$scope.validateData = function(allItems) {
    let isValid = true;
    let errorMessages = [];

    allItems.forEach(function(item, index) {
        if (!item.FirstName || !item.LastName || !item.Email) {
            isValid = false;
            errorMessages.push(`Missing required fields in item at index ${index}`);
        }

        if (item.Email && !emailValidator(item.Email)) {  // Assume emailValidator is a function to validate emails
            isValid = false;
            errorMessages.push(`Invalid email format in item at index ${index}`);
        }

        // Add more validation logic here
    });

    return { isValid, errorMessages };
};


In the example above, `emailValidator` could be a simple function that uses a regular expression to check if the email address is in a valid format. We're checking for missing required fields (`FirstName`, `LastName`, and `Email`) and invalid email formats. If any item fails these checks, we store an error message and set `isValid` to `false`.


Using the Validation Function

Before we proceed to save the data, let's make sure to call this validation function. Here's how to integrate it with the `$scope.saveCSV` function:

$scope.saveCSV = function(allItems) {
    let validation = $scope.validateData(allItems);

    if (validation.isValid) {
        return $http.post('/api/YourEndpoint/', {
            Data: JSON.stringify(allItems)
        });
    } else {
        console.log('Validation failed:', validation.errorMessages);
        // Handle validation errors here
    }
};

Conclusion

That’s it! You now have a way to validate your data before making that crucial POST request. It's a simple but powerful addition to your data manipulation arsenal. Good validation is like a solid foundation; it may not be the most exciting part of the construction process, but without it, you're always at risk of everything tumbling down. 

In the next post, I will talk about regex that can be used for the validation. 

Until then, happy coding!