如何在 Node.js 中处理表单验证,尤其是嵌套模型的验证?快递 +猫鼬 +玉
您如何使用 Express 和 Mongoose 处理表单验证?您使用的是自定义方法、某些插件还是默认错误数组?
虽然我可能会看到使用默认错误数组进行一些非常简单的验证,但在具有嵌套模型的情况下,这种方法似乎会崩溃。
How are you handling form validation with Express and Mongoose? Are you using custom methods, some plugin, or the default errors array?
While I could possibly see using the default errors array for some very simple validation, that approach seems to blow up in the scenario of having nested models.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我个人使用 node-validator 来检查用户的所有输入字段是否正确,然后再将其呈现给 Mongoose。
节点验证器还可以很好地创建所有错误的列表,然后将其呈现给用户。
I personally use node-validator for checking if all the input fields from the user is correct before even presenting it to Mongoose.
Node-validator is also nice for creating a list of all errors that then can be presented to the user.
Mongoose 有验证中间件。您可以单独为架构项定义验证函数。嵌套项目也可以被验证。此外,您可以定义异步验证。有关更多信息,请查看 mongoose 页面。
Mongoose has validation middleware. You can define validation functions for schema items individually. Nested items can be validated too. Furthermore you can define asyn validations. For more information check out the mongoose page.
我个人使用 express-form 中间件进行验证;它还具有过滤功能。它基于节点验证器,但对于 Express 有额外的好处。它向请求对象添加一个属性,指示其是否有效并返回错误数组。
如果您使用快递,我会使用这个。
I personaly use express-form middleware to do validation; it also has filter capabilities. It's based on node-validator but has additional bonuses for express. It adds a property to the request object indicating if it's valid and returns an array of errors.
I would use this if you're using express.