After failing data validation and reloading the page, value is displayed with unwanted whitespaces and new lines

Viewed 9

I want to create a blog post creation form. I have two fields in my form - title and content. If there was anything written in the fields and the data validation failed, then after reloading the page it should display the data that was inputted before failure. The data gets displayed again, but it comes with unwanted white spaces and new lines.

If I input one word without any white spaces and end lines, I get 4 lines with my word on the second line, with some white spaces before it and some white spaces on the other lines.

I don't really understand where the spaces are coming from.

Data is being returned only for content field right now. My form (I am using EJS):

<% let populateFields = false; %>
<% if(typeof blog_post !== 'undefined') { %>
  <% populateFields = true; %>
<% } %>

<h1>Create blog post</h1> 

<form action="" method="post">
<div class="mb-3">
  <label for="title" class="form-label">Title</label>
  <input class="form-control" name="title" id="title" value="">
</div>
<div class="mb-3">
  <label for="text" class="form-label">Content</label>
  <textarea class="form-control" name="content" id="content" rows="5">
    <% if(populateFields){ %>
      <%= blog_post.content %>
    <% } %>
  </textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>

<% if(typeof errors !== 'undefined'){ %>
  <div class="">
    <ul class="list-group">
      <% for(let i = 0; i < errors.length; i++){ %>
        <li class="list-group-item"><%= errors[i].msg %></li>
      <% } %>
    </ul>
  </div>
<% } %>

And my controller:

exports.create_post = [
body('title').trim().notEmpty().withMessage('Title is required')
.isLength({ max: 200 }).withMessage('Title is too long')
.escape(), 
body('text').trim().escape(),

(req, res) => {
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        res.render('admin/blog/create', { blog_post: req.body, errors: errors.array() });
        return;
    }
    res.redirect('/admin/blog');
}

]

0 Answers
Related