-Client-Side Form Validations
-Basic Error Handler
-Defining ExpressError Class
-More Errors
-Defining Error Template
-JOI Schema Validations
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.
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)
})
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)
}
})
app.use((err, req, res, next) => {
res.send(Something went wrong!)
})
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))
})
JOI Schema Validations
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}`)
}))
Top comments (1)
Iβm a huge fan of joi! Itβs a really good schema validator!