Question

I would like to perform server side validation, preferably with expressValidator. When saving a resource, I check to see if it is valid. If it's not valid what should I return?

There are examples: http://blog.ijasoneverett.com/2013/04/form-validation-in-node-js-with-express-validator/

https://github.com/ctavan/express-validator

Unfortunately, I can't figure out my answer from that.

In Angular, I am using the $resource service. When I do a save, and there is a validation error, how should the server send this back? Note, this is a single page application.

Also, how should I handle this on the client side? Is this technically a success call?

Please, I am not looking for any instant, ajax, check per field solution. I want to submit save, if there is a problem, I would like to return the errors so that Angular can handle them. This does not need to be the perfect solution, just something to set me on the right track.

I am not handing the Angular code in an special way at the moment: Controller:

$scope.saveTransaction = function (transaction) {
   transactionData.saveTransaction(transaction);
}

Service

saveTransaction: function(transaction) {
  return resource.save(transaction);
}

The server side code looks as follows:

app.post('/api/transactions', function (req, res) {
    var transaction; 

    req.assert('amount', 'Enter an amount (numbers only with 2 decimal places, e.g. 25.50)').regex(/^\d+(\.\d{2})?$/);

    var errors = req.validationErrors();
    var mapped = req.validationErrors(true);
    if (mapped) {console.log("MAPPED")};
    //console.log(mapped);

    if(!errors) {

        console.log("Passed");

        transaction = new TransactionModel({
            date: req.body.date,
            description: req.body.description,
            amount: req.body.amount
        });

        transaction.save(function (err) {
            if (!err) {
                return console.log("created");
            } else {
                return console.log("err");

            }
            return res.send(transaction);
        })
    }
    else {

        console.log("Errors");
        res.send(errors);
//        res.render('Transaction', {
//            title: 'Invalid Transaction',
//            message: '',
//            errors: errors
//        });

    }

});
Was it helpful?

Solution

You could send and handle "better" errors:

SERVER

res.json(500, errors)

CLIENT

resource.save(tran).then(function(){
  //it worked
},
function(response) {
  //it did not work...
  //see response.data
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top