【问题标题】:How to check by json file, if the input data are correct?如何通过json文件检查输入数据是否正确?
【发布时间】:2021-03-29 08:30:29
【问题描述】:

如何在使用 node.js 时通过包含数组/信息的 json 文件在 html 中验证用户的输入 (Product_ID)? 如果 Product_ID(在 Json 文件中)不存在/不正确,它应该警告错误消息。

例如:

数据.json

[
  {  
    "Product_ID": "887",
    "Name": "Name1",
  },
  {
    "Product_ID": "888",
    "Name": "Name2",
  }
]

product.html

<form id="product" action='/information.json' method="POST">
  <label class="product_ID">
    <input id="value" name="Proudct_ID" type="text" required/>
    <span class="placeholder">Enter product ID </span>
  </label>
</form>

信息.js

app.post('/information', (req, res) => {
  $.get.JSON('information.json', function(data) {
    document.write(data.Product_ID);
});

我不太清楚,如何在 information.json 中编写函数,以便在 information.json 文件中检查 Product_Id 并显示(错误)消息。 有任何想法吗?谢谢!

【问题讨论】:

  • 你的意思是information.js
  • 它是$.getJSON,但那是jQuery,即客户端代码。在节点中,您只需执行 const data = require('data.json');;现在您必须将name="product_id" 添加到您的 和action="/information" method="post" 到您的
    ,您可以检查req.body.product_id 和data。
  • 谢谢@ChrisG!我编辑了 html 文件。但我仍然不确定 information.js 文件。所以我不需要app.post('/information', (req..... 吗?我只是写 const data = require ('data.json') 来检查 json 文件中的数据是否存在?我需要在哪个地方进行显示/警报部分?如果您能给我一些建议,那就太好了。
  • 您绝对需要app.post(...) 部分来处理表单提交。加载 JSON 文件大部分与此无关,但需要在此之前进行,以便在您的节点代码处理表单数据时数据可用。但是,虽然我很乐意提供帮助,但您似乎缺乏基本的快递知识?如果是这样,帮助您相当于教您如何使用 express 和 POST 请求,这超出了 SO 问题的范围。
  • 谢谢@ChrisG。你是对的,我还不是专家,也不期待任何教学课:) 我只是有点困惑....我只是专注于解决我的主要问题,如何我可以通过json文件验证html中的输入。

标签: javascript html jquery json


【解决方案1】:

您好,我认为information.js 中可能存在问题

app.post('/information', (req, res) => {
  $.get.JSON('information.json', function(data) {
    document.write(data.Product_ID);
  }); // closing $.get.JSON function (I think you missed this one)
}); // closing app.post function 

除此之外,我建议您关注Joi validation。
如果您使用 NPM,它有一个 NPM package。 如果没有,您可以随时从GitHub 下载它

【讨论】:

  • 谢谢@TessavWalstijn。我从未听说过 Joi 验证。你认为在我的情况下更有意义吗?我正计划使用 node js / jquery ...
  • 有一个用于验证的 jquery 插件(通过谷歌搜索“jquery 验证”找到它)。我不知道你的项目是如何设置的,我不想说什么更好(事情可以通过不同的路线来实现)。我想确保您知道 jquery 在 javascript 框架生态系统中已经过时。建议使用 vanilla javascript 或任何 MVC 框架。注意:这并不意味着你不应该使用 jquery,你可以随意使用你想要的工具。
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2021-02-16
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
相关资源
最近更新 更多