Form validation (C# ASP MVC)

69 views
Skip to first unread message

Peter Morris

unread,
Jan 6, 2015, 1:43:23 PM1/6/15
to nod...@googlegroups.com
Hi all

I come from the ASP MVC C# world.  Over there I can add the following to a view @Html.ValidationMessageFor(x => x.Name) and if there is an error in my view state for that field it will output error text

ViewState.AddError('Name', 'Required');
return View();

It will also re-populate the input values of the form.  I'm looking to achieve something similar with Express.  Keeping the form values and also validating input + showing errors against form inputs.  Any advice would be appreciated!

Boris Yankov

unread,
Jan 6, 2015, 8:36:48 PM1/6/15
to nod...@googlegroups.com
Express does not do anything like this. 
It is much 'lower level' and nimble, and this type of validation goes outside its scope.

Peter Morris

unread,
Jan 7, 2015, 4:27:40 AM1/7/15
to nod...@googlegroups.com
I am hoping for middleware suggestions. I like express-validator, but now I just need a suggestion on how to default input() values to what was posted (and null if it is a GET request).

Peter Morris

unread,
Jan 7, 2015, 5:18:57 AM1/7/15
to nod...@googlegroups.com
I created the following plugin....

exports = module.exports = function (req, res, next) {
    var body = req.body;
    if (typeof body === 'undefined') {
        return next(new Error('form-values must be used after body-parser'));
    }
    var bodyKeys = Object.keys(req.body);
    res.locals.fv = function (name, defaultValue) {
        if (bodyKeys.indexOf(name) === -1) {
            if (typeof defaultValue === 'undefined') {
                return '';
            } else {
                return defaultValue;
            }
        } else {
            return req.body[name];
        }
    }
    return next();
};

Then to use it
var formValues = require('./lib/form-values');
app.use(formValues);

In the view
input(name="username", value="#{fv('username')}", type="text")

You can also use #fv('fieldName', 32)


Alexandre Laurent

unread,
Mar 9, 2015, 10:37:05 AM3/9/15
to nod...@googlegroups.com
I've just made a module that helps with validation and rendering of your forms (https://github.com/shaoner/torti), it can be extended and used with express.
Any feedback is welcome! 

Reply all
Reply to author
Forward
0 new messages