When we write data to a database, it is important to perform validation on the server side to ensure that the data is in the type and format that we expect it to be in. In this recipe, we will demonstrate how we can emit data to the server and emit messages back if there is a success or an error.
We will use promises to handle success and error states. Depending on your version of Node, you may need to install the promise module with npm install promise –save
. Promises are a feature of ES6, so they will eventually be native in Node.
To handle validation on the server side, follow these steps:
First, we will create a method for performing some validation on the server side. Typically, your validation would take place in your ORM, but we will perform it in plain JavaScript here to exhibit the concept. We will resolve a promise if the data is valid and reject the promise if it is invalid. Use the following code:
function validatePerson ...