part 14
We just separated out our validators, and now we need a way to display errors if the validations aren’t met…. We’re also going to get into putting some validations around the signin endpoint. To get started, we are first going to check to see if any errors occurred. In the signup post route, Im going to write an if statement for that check…. It sounds a little backward, but we are going to check to make sure that !errors.isEmpty(), Here its saying that errors is an empty array, when something goes wrong, the array is populated, so as long as its empty we are going to show the signupTemplate to which we pass in the req object, and the errors…

Doing this gives us the option to display the errors, now all we need to do, is to add the those errors to the views, so that its appended to the user experience. So navigate to the views/admin/auth/signup and and destructure out the errors object as well

Now its important to know that to make use of that object, we need to handle a check to ensure that there are any errors. When we are calling the signupTemplate in the auth.js file, its only getting passed the req object, which means that the errors object could be rendered as undefined at this point, so we are going to write a little helper function to make sure we dont get hung up on that. Right above the module.exports Im going to create a function getError that takes in the errors object and as a second argument it will receive the name of the property that has an error, so for now we will call it prop…

So now we need to run the check. Starting with an if statement we want to check for errors, and if there are errors, we want to map over the errors array and return the appropriate msg for that error, but there is a lot that can go wrong with that check and a lot of ifs we would have to cover, so to kind of cheat the check, Im going to actually use a try catch statement that will break if something is wrong and wont let us circumvent the if statement…

And now, we need to display the messages that we want… So now we need to call get error after each input, and pass the errors object, and as a second argument the specific property that we want and then we need to display the msg for that property…

And now, you should be able to go to the browser and enter some faulty credentials and you should see the error messages that we setup in the validators…


and there we have it… Not the prettiest, but effective and now we can keep moving on with the project, and remember… there will be a good amount of time spent making this look better but for now, functionality is whats important.