0

I am trying to achieve proper post validation which is eloquent and DRY when using Express.JS. What is the best way to do this properly?

Here is a code snipped where I trying make sure that this POST route will not crash the Node.js server and is type safe. But I feel that this is an ugly way to achieve this:

app.post('/signup', function(req, res) {
if(typeof req.body.name !== 'string' || typeof req.body.email !== 'string'  || typeof req.body.password !== 'string' ){
    res.status(400).send({status:400, message: 'Invalid json post format', type:'client'}); 
}else{  
    User.findOne({
        name: req.body.name
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
            User.findOne({
                email: req.body.email
            }, function(err, user) {

                if (err) throw err;

                if (!user) {
                    //both username and email are neither in use so lets create a user
                    var passwordToSave = bcrypt.hashSync(req.body.password, salt);

                    var user = new User({ 
                        name: req.body.name,
                        email: req.body.email,
                        password: passwordToSave,
                        admin: false 
                    });
                    user.save(function(err) {
                        if (err) throw err;

                        console.log('User created successfully');
                        res.json({ success: true });
                    });

                } else if (user) {
                    res.json({ success: false, message: 'Signup failed. Username already in use.' });
                }

            });         
        } else if (user) {
            res.json({ success: false, message: 'Signup failed. Username already in use.' });
        }
    });
}});
1

2 Answers 2

1

The Json schema standard (and any of various libraries that implement it) is a great DRY approach. The same validation can be done on both client and server side. What's more, you can even use jdorn's Json forms library to automatically generate the requisite html form from the schema!

Sign up to request clarification or add additional context in comments.

Comments

1

I highly recommend using Joi to be your validation tool

It super simple and east to adapt

In your scenario, what you need is

const schema = Joi.object().keys({
  name: Joi.string(),
  email: Joi.string(),
  password: Joi.string()
})

Joi.validate(req.body, schema);

you can also use more strict rule to validate your input, e.g. .email(), .min(), .mex(), etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.