Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does assert (req.assert) work in nodejs

I am currently working on MEAN stack using node, express and angularjs. I downloaded boiler plate code from mean.io and also using debugger while I explore the code.

In the controller which gets req and res as parameters, how does req.assert work?

In the file server/controllers/users.js

req.assert('username', 'Username cannot be more than 20 characters').len(1,20);

adds into validation error even when the username is empty or null. How do I check for current username value in the req? Where is the assert function of req defined.

I come from java background and find it tricky to find the function code some times as I wont be sure about where is it defined and how is it prototyped. How does one properly read the objects and browse the functions that are being used in javascript?

like image 217
raju Avatar asked May 01 '14 19:05

raju


People also ask

How does node js assert work?

The assert() method tests if a given expression is true or not. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated. The assert() method is an alias of the assert. ok() method.

Does console assert work in node js?

assert() Method. The console. assert() method is an inbuilt application programming interface of the console module which is used to assert value passed to it as a parameter, i.e. it checks whether the value is true or not and print an error message, if provided and failed to assert the value.

How do I import assert in node js?

For Node 10 and above, it's better to use strict assert which can be imported as named import and renamed for convenience as assert : import { strict as assert } from 'assert'; assert. ok(true); assert(true);

What is assert deepEqual?

The assert. deepEqual() method tests if two objects, and their child objects, are equal, using the == operator. If the two objects are not equal, an assertion failure is being caused, and the program is terminated.


2 Answers

It's defined in Express's dependency express-validator. Check here: https://github.com/ctavan/express-validator/blob/master/lib/express_validator.js

which depends on validator: https://github.com/chriso/validator.js

like image 135
Matt Avatar answered Sep 25 '22 07:09

Matt


Accepted answer refers to what is now the Legacy API hence broken links.

Check out the documentation for Sanitization and the available sanitizing tools. You can make custom validators in there.

like image 28
Steve Avatar answered Sep 24 '22 07:09

Steve