You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
5 Hrs
16 Min
38 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Solución del reto de validación

11/30
Resources

Data validation is a fundamental aspect in the development of RESTful APIs to guarantee the integrity and consistency of the information. Implementing proper validations at the POST and PUT endpoints prevents errors that could compromise the entire database and ensures that the application works correctly. These practices not only improve code quality, but also provide a better end-user experience.

How to implement effective validations in RESTful APIs?

When developing APIs, it is crucial to validate the data we receive before processing it. In this case, we have used artificial intelligence as a tool to generate robust validations for our endpoints. The implementation of these validations allows us to control the quality of the data entering our system.

The validations we have implemented include:

  • Email verification using regular expressions
  • Checking minimum length for user names
  • Validating that IDs are numeric and unique

These validations have been encapsulated in reusable functions that can be shared between the backend and frontend if necessary.

What validation functions should we implement?

The validation functions we have created are:

// Email validation using Regexfunction isValidEmail(email) { const emailRegex = /^[^^^^s@]+@[^^^s@]+@[^^^s@]+$/; return emailRegex.test(email);}
// Name validation (minimum 3 characters)function isValidName(name) { return typeof name === 'string' && name.length >= 3;}
// ID validation (numeric and unique)function isValidId(id, users) { const isNumeric = !isNaN(id); const isUnique = !users.some(user => user.id === id); return isNumeric && isUnique;}
// Main validation functionfunction validateUser(user, users) { const errors = [];  
 if (!isValidName(user.name)) { errors.push("Name must be at least three characters"); }  
 if (!isValidEmail(user.email)) { errors.push("The email is invalid"); }  
 if (!isValidId(user.id, users)) { errors.push("The ID must be numeric and unique"); } }  
 return { isValid: errors.length === 0, errors: errors };}

These functions are stored in a file called validation.js inside the utilities folder, allowing them to be easily imported anywhere in our application.

How to integrate validations in the endpoints?

To integrate these validations in our POST and PUT endpoints, we need to import the main function validateUser and use it before processing the data:

import { validateUser } from './utils/validation.js';
// In the POST endpointapp.post('/users', (req, res) => { const newUser = req.body; const validation = validateUser(newUser, users);  
 if (!validation.isValid) { return res.status(400).json({ error: validation.errors }); }  
 // Continue with the logic to create the user users.push(newUser); res.status(201).json(newUser);});
// At the PUT endpointapp.put('/users/:id', (req, res) => { const updatedUser = req.body; const validation = validateUser(updatedUser, users);  
 if (!validation.isValid) { return res.status(400).json({ error: validation.errors }); }  
 // Continue with the logic to update the user // ...});

How to test the implemented validations?

To verify that our validations work correctly, we can use tools like Postman to send different types of requests to our endpoints:

  1. Successful case: send valid data that comply with all validation rules.
  2. Duplicate ID: Attempting to create a user with an ID that already exists.
  3. Short name: Send a name with less than three characters.
  4. Invalid email: Providing an incorrectly formatted email.

By testing these cases, we should receive appropriate responses:

  • For successful cases: code 201 (Created) and the user data.
  • For cases with validation errors: code 400 (Bad Request) and specific messages about the errors encountered.

What challenges can arise with these validations?

A common challenge is the validation on the PUT endpoint. As observed in testing, there can be a conflict when trying to update an existing user, as the unique ID validation might reject the operation incorrectly.

This is an interesting challenge: to modify the validation function to allow updating an existing user without the unique ID validation interfering. A possible solution would be to adapt the isValidId function to consider the context of the operation (creation vs. update).

Implementing robust validations is a fundamental step in building reliable and secure APIs. These practices not only prevent data errors, but also improve the user experience by providing clear and specific error messages. Have you faced similar challenges in your projects? Share your experiences and solutions in the comments.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Mi solución para el bug en el update fue usar las funciones de validación separaradas `if (!isValidEmail(changes.email) && !isValidName(changes.name)) {      return res.status(400).json({ error: validsation.error });    }`