DEV Community

Code_Regina
Code_Regina

Posted on

|YelpCamp| Errors and Validating Data

              -Client-Side Form Validations
              -Basic Error Handler 
              -Defining ExpressError Class 
              -More Errors 
              -Defining Error Template 
              -JOI Schema Validations 
Enter fullscreen mode Exit fullscreen mode

Client-Side Form Validations

It is important to add client-side validation to the forms, to ensure that end users are entering correct data into the fields.

One way to do this, is to include the word required on the html forms.
Alt Text

there is also a way to provide client-side validation with javascript

const forms = document.querySelectorAll('.validation-forms') 

Array.from(forms)
  .forEach(function (form) {
   form.addEventListener('submit', function (event) {
  if (!form.checkValidity()) {
    event.preventDefault() 
    event.stopPropagation()
  }

 form.classList.add('was-validated')
}, false) 

})

Enter fullscreen mode Exit fullscreen mode

Basic Error Handler

First set up the try catch block in the async function and then set up the error handler.


app.post('./campgrounds', async (req, res, next) => {
  try {
      const campground = new Campground(req.body.campground); 
      await campground.save();
      res.redirect(`/campgrounds/${campground._id}`)
} catch (e) {
    next(e)
  }
 })

Enter fullscreen mode Exit fullscreen mode

app.use((err, req, res, next) => {
  res.send(Something went wrong!)
})

Enter fullscreen mode Exit fullscreen mode

Defining ExpressError Class

Create a new folder called utils
then a file called ExpressError.js


class ExpressError extends Error {
 constructor(message, statusCode) {
  super(); 
  this.message = message;
  this.statusCode = statusCode; 

  }
}

module.exports = ExpressError; 


###More Errors 

app.use((err, req, res, next) => {
  const { statusCode = 500, message = 'Something went wrong' } = err; 
  res.status(statusCode).send(message); 
 })



app.all('*', (req, res, next) => {
 next(new ExpressError('Page Not Found', 404))
 })

Enter fullscreen mode Exit fullscreen mode

JOI Schema Validations

https://joi.dev/api/?v=17.2.1

app.post('/campgrounds', catchAsync(async (req, res, next) => {
  const campgroundSchema = Joi.object({
    campground: Joi.object({
        title: Joi.string().required(), 
        price: Joi.number().required().min(0),
   }).required()

 })

  const campground = new Campground(req.body.campground);
  await campground.save(); 
  res.redirect(`/campgrounds/${campground._id}`)
}))

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jvarness profile image
Jake Varness

I’m a huge fan of joi! It’s a really good schema validator!