Another aspect of input sanitization is data sanitization. Data sanitization is the process of removing all dangerous characters from an input string before passing it to the SQL engine. For example, we can remove unwanted characters or spaces that might lead to a SQL injection. validator.js
includes functions to clean up data inputs.
We can use validator.normalizeEmail()
function to remove formatting on email inputs to remove potentially dangerous characters. For example:
console.log(validator.normalizeEmail(" [email protected]"))
The above code will print out [email protected]
.
We can use the validator.escape()
function to replace <
, >
, &
, '
, and "
characters that could be confused with HTML entities. For example:
console.log(validator.escape("1 < 2"))
The above code will print 1 < 2
.
View the documentation page for a list of all sanitizer functions available.
We’ll be using the same email and password forms and sanitizing their values.
Instructions
Start the server by running node app.js
inside the bash Terminal and refreshing the mini browser.
Inside the response object in the /email
route’s callback function, use the normalizeEmail()
from Validator.js to remove email formatting from the form named emailForm
.
Press the Check Work button to check your work for each checkpoint.
Inside the response object in the /date
route’s callback function, use the toDate()
function from validator.js
to convert dateForm
from a string to a date.
Inside the response object in the /escape
route’s callback function, use the escape()
function from validator.js
to escape special characters from the form named escapeForm
.
Start the server by running node app.js
in the terminal. If the server is already running, you can stop it by typing Ctrl + C and typing node app.js
again.
Reload the workspace browser, and try submitting different form values to see their sanitized values.
- In the email form, try submitting:
[email protected]
- In the date form, try submitting:
1/1/2021
- In the escape form, try submitting:
I <3 coding!