Learn

One step of input sanitization is validating data input. Data validation is a process where a web-form checks if the information adheres to the expected format. validator.js provides many methods to check whether a string is a valid type. It can validate different types, ranging from dates to email addresses.

Here are some of the ways we can validate input using validator.js:

  • isEmail() - Checks if the input is a valid email address.
  • isLength() - Checks if the input is a certain length. An object with min and max can be passed as an argument.
  • isNumeric() - Checks if the input is numeric.
  • contains() - Checks if the input contains a certain value.
  • isBoolean() - Checks if the input is a boolean value.
  • isCurrency() - Checks if the input is currency-formatted.
  • isJSON() - Checks if the input is JSON.
  • isMobilePhone() - Checks if the input is a valid mobile phone number.
  • isPostalCode() - Checks if the input is a valid postal code.
  • isBefore() and isAfter() - Checks if a date is before or after another date.

We can use validator.js functions in a post route to validate data that is sent inside a request. The following example extracts the value from a form named “email” and logs whether it is a valid email address.

app.post('/submit', (req, res) => { console.log( validator.isEmail(req.body.email)); })

If you’d like to run the application, type node app.js into the bash Terminal and then refresh the mini browser.

Instructions

1.

Inside the response object in the /submit route’s callback function, use Validator.js to determine if req.body.email is an email address.

Press the Check Work button to check your work for each checkpoint.

2.

Inside the response object in the /submit route’s callback function, use validator.js to determine if req.body.password is a valid length from 5-10 characters long using the isLength() function from validator. An object can be passed as an additional argument, to validate whether a string s a valid length. The object can have the min and max properties like this:

validator.isLength(req.body.input, { min: 1, max: 100 });
3.

Start the server by running node app.js in the bash Terminal.

Then, reload the workspace browser and test form input values to see if the values are valid.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?