Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
How to validator register API nodejs?

Forgive me for my limited knowledge. My problem is that I have made the code below myself. When it comes to validator email, address, phone, .., I don't know how to handle it. I have found some documents to read that I do not understand.Please help me! Thanks very much!

userService.js

exports.findUserResgiter = async (email) => {
    var result = null;
    try{
        result = await User.findOne({
            email: email, 
        })
    } catch(e){}

    return result;
};

userModels.js

const UserShema = new Shema({
    name: String,    
    date_of_birth: Date,   
    address: String,  
    phone: String,    
    email: String,  
    password: String 
}, {
    collection: 'users' 
});

userController.js

exports.register = async (req, res, next)=>{
var email=req.body.email; 
var password=md5(req.body.password) 
var name=req.body.name 
var address=req.body.address 
var phone=req.body.phone 
var date_of_birth=req.body.date_of_birth 


var data = await userService.findUserResgiter(email);
console.log(data);
if(data === null){
    res.status(200).json({message: "null"});
    return User.create({ 
        name: name, 
        email: email, 
        password: password, 
        address: address, 
        date_of_birth: date_of_birth, 
        phone: phone, 
    }) 
}else{
    res.status(401).json({message: "This email already exists!"});
}

};

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There are loads of libraries that can help you out with validation. Try something like Joi or Superstruct . Here's a basic example using Joi since it's quite popular:

I assume you're using express? So first I'm gonna write some middleware that checks the req.body against a schema:

export function validateResource(schema) {
 return (req, res, next) => {
  try {
   schema.validate(req.body);
   //move to next middleware if validation success
   next();
  }
  catch(err) {
   //pass to an error handling middleware
   next(err);
   //or send bad request status code
   res.sendStatus(400);
  }
}

Then define your schema:

const Joi = require('joi');

const userSchema = Joi.object({

 name: Joi.string().required(),    
 email: Joi.string().email().required(),  
 password: Joi.string().required(),
 //etc.... refer to the docs for other validation methods, there are loads
});

Use the middleware like so:

//require your userSchema

app.post("/some_endpoint", validateResource(userSchema), (req, res, next) => {
 //at this point in the code, the data is validated
}

You can reuse the validateResource middleware with any schema you define.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda