Node.js server-side check from the client side

Express-form is a pretty powerful validation plugin for node.js / express. However, in the examples and documentation, the whole answer is server-side (console.log), which is enough for development, but it is not very practical to tell the user what is wrong.

At the moment, I can present two different solutions:

  • Submit the form and redirect / visualize the form again with req.body and validation messages attached to add "errors" to the wrong fields.
  • Submit the form using AJAX.

I would prefer option 2, since I don't want to query the database again when rendering 'new'. But I need to think about how to pass the test results back to the client and add β€œerrors” to the input fields.

Any ideas?

+4
source share
1 answer

I try to check the user login through javascript in the first instance in the browser, and then check on the server the error output in the visualized form (a la rails). Now I use my own set of custom validators, so I can not point you in the right direction using express-form .

Along with my custom regular expressions, I sometimes use the validator package npm, you can also use validator validator in the browser using a simple DOM or some structure.

edit:

working with AJAX checks is quite simple: you get the object in your request (if you use express.bodyParser() middleware), check the parameters if there are some errors that you can point to it in the ex answer.

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

and

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

If you use the browser-side framework, there are plugins, or I'm sure it's easy to write.

+3
source

Source: https://habr.com/ru/post/1396597/


All Articles