Validation for Reviews

 WE COULD BE ABLE TO SEND EMPTY DATA FOR REVIEWS.INORDER TO STOP THIS WE VALIDATE THE REVIEWS.

2 VALIDATIONS

CLIENT SIDE AND SERVER SIDE

CLIENT SIDE

 <form action="/listings/<%=listing._id%>/reviews" method="post"class="needs-validation"novalidate>
        <div class="col-8 offset-2 mb-2 mt-3">
          <label for="rating" class="form-label">Rating</label>
          <input
            type="range"
            min="1"
            max="5"
            id="rating"
            name="review[rating]"
            class="form-range"
            required
          />
        </div>
        <div class="col-8 offset-2">
          <label for="comment" class="form-label">Comments</label>
          <textarea
            name="review[comment]"
            id="comment"
            rows="5"
            cols="30"
            class="form-control"
            required
          ></textarea>
          <div class="invalid-feedback">Add a valid Review!</div>
        </div>

        <button class="btn btn-outline-dark offset-2 mb-2 mt-3">submit</button>
      </form>

BROWSER STYLING

WE ADD BOOTSTRAP STYLING


USING HOPPSCOTCH WE CAN STILL EMPTY DATA ,SO WE USE SERVER SIDE VALIDATION

SERVER SIDE VALIDATION

SCHEMA.JS

module.exports.reviewSchema = Joi.object({
  review: Joi.object({
    rating: Joi.number().required().min(1).max(5),
    comment: Joi.string().required(),
  }).required(),
});


IN APP.JS  REVIEWSCHEMA IS REQUIRED.

const { listingSchema, reviewSchema } = require("./schema.js");

VALIDATEREVIEW IS CREATED.


const ValidateReview = (req, res, next) => {
  let { error } = reviewSchema.validate(req.body);
  if (error) {
    let errMsg = error.details.map((el) => el.message).join(",");
    throw new ExpressError(400, errMsg);
  } else {
    next();
  }
};


TO ENABLE VALIDATION ValidateReview IS ADDED.

// REVIEWS
app.post(
  "/listings/:id/reviews",
  ValidateReview,
  wrapAsync(async (req, res) => {
    let { id } = req.params;
    let listing = await Listing.findById(id);
    let newRev = new Review(req.body.review);
    console.log(newRev);

    await newRev.save();
    listing.reviews.push(newRev);
    await listing.save();

    console.log("review saved");
    res.redirect(`/listings/${id}`);
  })
);



Comments