Patrick Patrick - 9 months ago 74
Ajax Question

Node.js server-side form validation with client-side response

Express-form is a quite powerful validation plugin for node.js/express. However, in the examples and documentation, all response is server-side (console.log), which is enough for development, but not quite practical to tell the user what's wrong.

At the moment, I can imagine two different solutions:

  1. Submit the form and redirect back / render the form again with req.body and validation messages attached to add 'error'-classes to wrong fields.

  2. Submit the form using AJAX.

I would prefer option 2, as I don't want to query the database again when rendering 'new'. But I have to idea how to pass the validation results back to the client and add 'error'-classes to input fields.

Any ideas?

Answer Source

I try to validate user input via javascript in the first instance in the browser, and then validate on the server outputting errors in the rendered form (a la rails). Right now I'm using my set of custom validators so I can't point you in the right direction with express-form.

Along with my custom regexes I, sometimes, use the validator npm package, you can also use the validator validations in the browser using plain DOM or some framework.


working with AJAX validations is quite easy, you receive an object in your request (if you use express.bodyParser() middleware), validate the parameters, if there are some errors you can point at it in your response ex.

"errors": {
    "foo": "must be a number"


for (i in answer.errors) {
  var target = document.getElementById(i);
  target.class = "error";
  // here you can also handle the error description

If you are using a framework on the browser side, there are plugins or I'm sure it's simple to write one.