简体   繁体   中英

Displaying server side validation error message on a bootstrapped ejs form

I am trying to conditionally display an error message if a user enters a URL string which isn't a valid URL into a bootstrap form field.

From the validationResult I am sending the errors over to the EJS template as an array of error objects as per express-validator docs. I have other form fields being validated as well so there could be more than one error in the array.

app.post('/create', [
  body('imgURL').isURL()
    .withMessage(‘Must be valid URL’)
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.render(‘form’, { errors: errors.array() });
  }
})

In my EJS template Im using standard bootstrap client side validation but also want to be able to display server errors as well. How can I conditionally render the invalid-feedback div with the server message. And also toggle the input element class 'is-invalid'?

Since errors might be an array do I have to loop through the array and check the error object param field (ie error.param === 'imgURL')? Would I have to repeat this loop for every form field?

<div>
 <label for="imgURL">Image URL</label>
 <input type="text" class="form-control is-invalid" id="imgURL" required>
  <div class="invalid-feedback">  
    Message sent from server here.   
  </div>
</div>

Alternatively is there a better way? Thanks!

Yes you have to. But instead of making loop in template file, you can do it in controller file (js file).

Create a function, the function will check input valid by input id, then pass the function to template file.

  const getInputError = (inputName) => {
    return errors.array().find(i => i.param === inputName || i.body === inputName);
  }
  res.render('form', { getInputError });

In template file, just call the function and check it's result:

  <div>
    <label for="imgURL">Image URL</label>
    <% const imgURLError = getInputError('imgURL'); %>
      <input type="text" class="form-control <%= imgURLError ? 'is-invalid' : '' %>" id="imgURL" required>
      <% if (imgURLError) { %> 
      <div class="invalid-feedback">
        <%= imgURLError.msg %> 
      </div>
      <% } %>
  </div>

You have do the same for another input field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM