DEV Community

Cover image for Top 10 Smart Ways to Use API Validation in Node.js
Suresh Pattu
Suresh Pattu

Posted on • Edited on

Top 10 Smart Ways to Use API Validation in Node.js

Are you building web applications with Node.js and Express.js? Handling user input is a crucial part of web development, and ensuring that the data your application receives is valid and safe is paramount. Meet express-validator, a powerful npm package that simplifies the process of validating and sanitizing user input in your Express.js applications.

Here are some use cases :

1. User Registration Form

You can use the express validator to validate user registration data, including fields like username, email, password, and password confirmation. Ensure that usernames meet certain criteria, email addresses are valid, and passwords meet security requirements.

const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
app.use(express.json());

// Define an API route for user registration
app.post('/register', [
  // Validate and sanitize the 'username' field
  body('username').isLength({ min: 5 }).trim().escape(),

  // Validate and sanitize the 'email' field
  body('email').isEmail().normalizeEmail(),

  // Validate the 'password' field
  body('password').isLength({ min: 6 }),
], (req, res) => {
  // Perform the validation by checking for errors
  const errors = validationResult(req);

  // If there are validation errors, respond with a 400 Bad Request status
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // If validation is successful, handle the registration logic here
  const { username, email, password } = req.body;
  // ... Your registration logic ...

  // Respond with a success message or redirect as needed
  res.status(200).json({ message: 'Registration successful' });
});

// Start the Express server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

2. Product Review Submission

When users submit product reviews, you can validate the review content, star rating, and any optional fields. Ensure that the review text is not empty and the star rating falls within a valid range.

body('reviewText').trim().notEmpty();
body('rating').isInt({ min: 1, max: 5 });
Enter fullscreen mode Exit fullscreen mode

3. Search Query Validation

For search functionality, validate the user's search query to prevent potential security issues. Ensure that the query is not excessively long and contains only safe characters.

query('q').isLength({ max: 50 }).matches(/^[a-zA-Z0-9\s]+$/);
Enter fullscreen mode Exit fullscreen mode

4. File Uploads

When users upload files, validate the file type, size, and any additional criteria. Ensure that uploaded files meet your application's requirements.

const { body, file } = require('express-validator');

file('avatar').custom((value, { req }) => {
  if (!isValidFileType(value.mimetype)) {
    throw new Error('Invalid file type');
  }
  if (value.size > 1048576) {
    throw new Error('File size exceeds 1MB');
  }
  return true;
});
Enter fullscreen mode Exit fullscreen mode

5. Comment Submission

For blog or forum comments, validate the user's comment text to prevent issues like spam. Ensure that the comment is not empty and doesn't contain prohibited content.

body('commentText').trim().notEmpty().custom(value => {
  if (containsProhibitedContent(value)) {
    throw new Error('Prohibited content detected');
  }
  return true;
});
Enter fullscreen mode Exit fullscreen mode

6. Payment Form

In a payment form, validate credit card information, including card number, expiration date, and CVV. Ensure that the card number is valid and the expiration date is in the future.

body('cardNumber').isCreditCard();
body('expirationDate').isDate().isAfter(new Date().toISOString());
body('cvv').isInt({ min: 100, max: 999 });
Enter fullscreen mode Exit fullscreen mode

7. Location-based Services

For location-based services, validate user input like postal codes, coordinates, and addresses to ensure they match expected formats.

body('postalCode').matches(/^\d{5}$/);
body('latitude').isFloat({ min: -90, max: 90 });
body('longitude').isFloat({ min: -180, max: 180 });
Enter fullscreen mode Exit fullscreen mode

8. API Request Parameters

When building an API, validate request parameters, query strings, and request headers to ensure that they meet the required format and data types.

param('productId').isMongoId();
query('limit').isInt({ min: 1, max: 100 });
header('authorization').isJWT();
Enter fullscreen mode Exit fullscreen mode

9. User Profile Updates

When users update their profiles, validate the changes they make, including fields like username, email, and profile picture.

body('username').isAlphanumeric().isLength({ min: 5 });
body('email').isEmail();
file('profilePicture').optional().custom((value, { req }) => {
  if (value && !isValidFileType(value.mimetype)) {
    throw new Error('Invalid file type');
  }
  return true;
});
Enter fullscreen mode Exit fullscreen mode

10. Custom Validation Logic

You can implement custom validation logic for specific use cases, such as validating API tokens, verifying data uniqueness, or checking complex business rules.

body('apiToken').custom(async value => {
  if (!isValidApiToken(value)) {
    throw new Error('Invalid API token');
  }
  return true;
});
Enter fullscreen mode Exit fullscreen mode

These diverse use cases showcase the flexibility and power of the "express-validator" package in handling a wide range of validation requirements in your Node Js application. Whether you're building a user registration form, an API, or any other web application feature, express-validator can help you ensure data integrity and security.

Top comments (0)