Node.js 空输入验证无效
我在尝试使用以下脚本验证输入时遇到了一些问题Node.js 空输入验证无效,node.js,coffeescript,connect,Node.js,Coffeescript,Connect,我在尝试使用以下脚本验证输入时遇到了一些问题 app = connect() .use(connect.bodyParser()) #So we can get the post data. .use(req,res) -> valid = false if (req.body.name is "") or (req.body.question is "") or (req.body.email is "") #Was all the data submitted?
app = connect()
.use(connect.bodyParser()) #So we can get the post data.
.use(req,res) ->
valid = false if (req.body.name is "") or (req.body.question is "") or (req.body.email is "") #Was all the data submitted?
if valid
#process request
http.createServer(app).listen(1407)
为了进行调试,我使用console.log列出了输入,其中它返回两个输入,一个数据正确,另一个未定义
我以前也使用了req.body.name?
,但它只是重写为req.body.question!=null
且不检查是否存在未定义
HTML表单
<form action="_serverurl_" method="post">
<input type="text" placeholder="Your Name" name="name">
<input type="text" placeholder="Your Email" name="email">
<input type="text" placeholder="Subject" name="subject">
<textarea name="question" placeholder="Question"></textarea>
<div class="right"><input type="submit" class="submit" name="submit" value="Send"></div>
</form>
最让我困惑的是为什么服务器有两个输入
调试信息:
- 节点版本:v0.10.21
- 连接版本:v2.12.0
isFieldValid
)
如果您正在寻找一个更复杂的验证库,我建议您使用
希望这能有所帮助。效果很好,我不知道为什么它以前从未出现过。我也没有意识到您可以使用
{name,etc}=req.body
来引用创建变量,真正的帮助!谢谢@Daniel您可能对手册的这一部分感兴趣。伙计们,最后一个。在问答中使用(
语句缺少它的)
。如果你把这个留在互联网上,你可能会破坏谷歌。(我会删除(
,因为唯一/最后一个参数是回调函数。)
isFieldValid = (field) -> field? and field.length > 0
app = connect()
.use(connect.bodyParser()) #So we can get the post data.
.use (req,res) ->
# pickup the body vars first to ease reading
{name, email, subject, question} = req.body
# valid should be always defined, even if it's only true/false
# Was all the data submitted?
valid = isFieldValid(name) and isFieldValid(email) and isFieldValid(question)
if valid
# process request
else
# handle invalid data
res.send(400, ...)