验证提交的表单并正常显示错误

时间:2019-02-10 14:33:02

标签: express mongoose ejs mongoose-schema

我正在尝试验证用户提交的表单并显示有意义的错误,但是我有很多问题。首先,我的表单(event_form.ejs):

<% if (typeof errors !== 'undefined') { %>
    <div class="message"><%= errors %></div>
<% } %> 

<form method="POST" action="/submit-create-event" id="create-event">
  <input type="text" class="title" name="title" placeholder="title">
  <input type="text" class="date" autocomplete="off" name="date" placeholder="date">
  <select class="type" name="type">
    <option value="road">Road</option>
    <option value="mtb">MTB</option>
  </select>
  <input type="text" class="city" name="city" placeholder="city">
  <select class="level" name="level">
      <option value="beginner">Beginner</option>
      <option value="advanced">Advanced</option>
      <option value="pro">Pro</option>
  </select>
  <input type="text" class="start-time timepicker" autocomplete="off" data-time-format="H:i" name="startTime" placeholder="start time">
  <input type="text" class="start_location" name="startLocation" placeholder="start location">
  <input type="text" class="distance" name="distance" placeholder="distance">
  <input type="submit" class="create-event-submit">
</form>

提交后,在我的eventController.js中,我具有处理提交的功能。

//Helper function to handle event form submit.
module.exports.submitEventForm = function(req, res) {

  const event = new eventModel.event({
    title: req.body.title,
    date: req.body.date,
    type: req.body.type,
    city: req.body.city,
    level: req.body.level,
    start_time: req.body.startTime,
    start_location: req.body.startLocation,
    distance: req.body.distance
  });

  event.save(function(err, data) {
    if (err) {
      console.log(err);
      //I tried this, kinda works but pretty sure a bad practice
      res.render('forms/create_event_form', {errors: err})
    } else {
      res.render('status/success');
    }
  });
};

如您所见,在event.save()上如果我有错误,我现在console.log()。我尝试做的是再次渲染event creation表单并显示错误(在.ejs文件中可见)。非常确定不应该那样做。

这是我的model文件,其中一个validator

var mongoose = require('mongoose')
var validate = require('mongoose-validator')
var Schema = mongoose.Schema;


var titleValidator = [
  validate({
    validator: 'isAlphanumeric',
    message: 'Title should be alphanumeric'
  })
]

var eventSchema = new Schema({
  title: {type: String, required: true, validate: titleValidator},
  date: {type: String },
  type: {type: String },
  city: {type: String },
  level: {type: String },
  start_time: {type: String },
  start_location: {type: String },
  distance: {type: Number },
});

var Event = mongoose.model('Event', eventSchema);

module.exports.eventSchema = eventSchema;
module.exports.event = Event;

我创建了titleValidator,如果我的表单失败,它将打印出如下内容:

Error message on incorrect tilte

我的问题是:如何正确地将validator消息发送到模板并显示?如何再次创建validators来处理多条消息,因为错误不会以array的方式返回,这意味着我无法遍历它们?

1 个答案:

答案 0 :(得分:0)

Kinda找到了解决方案。为了使错误消息更具可读性和可用性,我使用了Mongoose error helper。它整齐地打印出所有错误消息。 但是,当通过npm获取软件包时,代码中存在错误,并且为解决方案创建了pull request,但从未合并。只需手动进行较小的更改。

我找不到其他方法来渲染带有错误的相同表单,所以我坚持这一点:

event.save(function(err) {
    if (err) {
      res.render('forms/create_event_form', {errors: errorHelper(err, next)});
    } else {
      res.render('status/success');
    }
  }); 

在我的.ejs模板中,我打印出如下错误:

<% if (typeof errors !== 'undefined') { 
   errors.forEach(function(err) { %>
    <div class="message"><%= err %></div>
<% })} %> 

希望这可以帮助某人,加油。