【问题标题】:Empty input validation not working空输入验证不起作用
【发布时间】:2014-02-07 21:07:21
【问题描述】:

我在尝试获取以下脚本来验证输入时遇到了一些问题。

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 列出输入,它返回两个输入,一个带有正确数据,另一个 undefined

我之前也使用过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

【问题讨论】:

    标签: node.js coffeescript connect


    【解决方案1】:

    实际上,我不明白为什么您的代码不起作用,但一种方法可能是将其拆分为更小的可管理组件。 对于验证,您可以定义一个函数,该函数允许您确定字段是否有效(请参阅下面的isFieldValid)。

    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, ...)
    

    如果您正在寻找更精细的验证库,我建议您使用 Validator

    希望对您有所帮助。

    【讨论】:

    • 完美运行,我不知道为什么以前从来没有。我也没有意识到您可以使用{name, etc} = req.body 来引用创建变量,真正的帮助!谢谢!
    • @Daniel 您可能对手册中的Destructuring Assignment 部分感兴趣。
    • 伙计们,最后一个.use( 声明在问题和答案中都缺少其)。如果你把它留在互联网上,你可能会破坏谷歌。 (我会放弃(,因为唯一/最后一个参数是回调函数。)
    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多