node.jscoffeescriptnode.js-connect

Empty input validation not working


I have been having a few issues trying to get the following script to validate inputs.

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)

In order to debug I have used console.log to list the inputs, where it returns two inputs, one with the correct data and another undefined

I was previously using req.body.name? as well, but it is only rewriting as req.body.question != null and not checking for undefined.

The HTML form

<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>

The part confusing me the most is why there are two inputs to the server?

Debug info:


Solution

  • Actually I can't see why your code would not work, but an approach may be splitting it into smaller manageable components. For validation you could define a function, that allows you to determine whether a field is valid or not (see isFieldValid below).

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

    If you're looking for a more elaborate validation library I'd recommend Validator.

    Hope that helps.