0

I have a form to validate. When I type something wrong, it must alert, but when I fill the form, it returns [Object object]. What is the reason my code does not work properly and how should I put the data?

enter image description here

router:

router.post('/post', [
    check('title')
        .trim()
        .notEmpty()
        .matches(/^[a-zA-Z ]*$/)
        .withMessage('Title must not be empty.')
        .isLength({ min: 5 })
        .withMessage('Title must be at least 5 characters.')
        .isLength({ max: 40 })
        .withMessage('Title can not be longer than 40 characters.'),

    check('content')
        .trim()
        .notEmpty()
        .matches(/^[a-zA-Z ]*$/)
        .withMessage('Title must not be empty.')
        .isLength({ min: 30 })
        .withMessage('Title must be at least 30 characters.')
        .isLength({ max: 30000 })
        .withMessage('Title can not be longer than 30000 characters.')
], async (req, res) => {
    const errors = validationResult(req)
    if(!errors.isEmpty()){
        res.render('post', {errors: errors.array()})
    } else{
        const article = new articles({
            title: req.body.title,
            content: req.body.content
        })
    
        await article.save()
        res.redirect('/')
    }
})

page:

<form action="/post" method="POST" class="p-3 mt-5 mx-auto" style="max-width: 768px;">
  <h1 class="text-black-50 text-center font-weight-bold mb-5">Make Your Post</h1>
  {{#if errors.length}}
    <ul class="alert alert-danger pl-5" role="alert">
      {{#each errors}}
        <li>{{this}}</li>
      {{/each}}
    </ul>
  {{/if}}
  <div class="form-group">
    <input autocomplete="off" type="text" class="form-control" id="title" name="title" placeholder="Enter a title" onchange="saveValue(this)">
  </div>
  <div class="form-group">
    <textarea style="resize:none" rows="8" type="text" class="form-control" id="content" name="content" placeholder="Start writing text..."></textarea>
  </div>
  <button id="submit" type="submit" class="btn btn-success w-100 mt-3">Submit</button>
</form>

Amount of the errors is right, but I don't know what am I doing wrong when I put data.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Anisimov
  • 25
  • 1
  • 8
  • Does this answer your question? [How can I display a JavaScript object?](https://stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object) – about14sheep Sep 17 '22 at 20:06
  • The error is for sure an object, you probably have to display a specific param of the object like {{this.description}} or something like that – Guillaume Sep 17 '22 at 20:08
  • @Guillaume, oh, right. Thank you! The problem is solved. – Anisimov Sep 17 '22 at 20:43

1 Answers1

1

@Guillaume solved the problem. I had to write not {{this}}, but {{this.msg}}.

Anisimov
  • 25
  • 1
  • 8