question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Asynchronous Validation - Validating If Username Exists.

See original GitHub issue

Hi,

I’m having a problem using Async functions to validate whether a username exists.

server.js

app.use(validator({

    customValidators: {

        isUsernameAvailable: function(username) {
            return new Promise(function(resolve, reject) {

                User.findOne({'username': username}, function(err, results) { 

                    if(err) {
                        return resolve(err);
                    }
                    reject(results);

                });

            });
        }
    }

}));

auth.middleware.js

module.exports.register = function(req, res, next)
{
    req.checkBody({

        'username': {
            notEmpty: true,
            errorMessage: 'Username is required'
        },

        'email': {
            notEmpty: true,
            isEmail: {
                errorMessage: 'Invalid Email Address'
            },
            errorMessage: 'Email is required'
        },

        'password': {
            notEmpty: true,
            errorMessage: 'Password is required'
        },

        'password_confirmation': {
            notEmpty: true,
            errorMessage: 'Password Confirmation is required'
        }

    });

    req.assert('password_confirmation', 'Passwords do not match').equals(req.body.password);

    req.check('username', 'This username is already taken').isUsernameAvailable();

    req.asyncValidationErrors().catch(function(errors) {

        if(errors) {
            return res.json({
                success:false,
                errors: errors
            });
        };
    });

    var errors = req.validationErrors(true);

    if(errors) {

        return res.json({
            success: false,
            errors: errors
        });

    }

    next();
}

auth.controller

module.exports.register = function(req, res) {

    var input = req.body;

    var user = new User({

        username: input.username,
        email: input.email,
        password: input.password

    });

    user.save(function(err) {

        if(err) {
            return res.json(err);
        }

        return res.json({
            success: true,
            status: 'Successfully Registered User'
        });

    });

}

auth.route


router.post('/register', middleware.register, controller.register);

My server crashes with:

WARNING: You have asynchronous validators but you have not used asyncValidateErrors to check for errors.

Error: Can’t set headers after they are sent.

its trying to set headers because its called next() when i actually want it to return the error and stop.

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:1
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
jalfcolombiacommented, Feb 17, 2016

Hello, I’ve been able solved. Thanks @Jakeii. Thanks to this link

The file is as follows

auth.middleware.js

module.exports.register = function(req, res, next)
{
    req.checkBody({

        'username': {
            notEmpty: true,
            errorMessage: 'Username is required'
        },

        'email': {
            notEmpty: true,
            isEmail: {
                errorMessage: 'Invalid Email Address'
            },
            errorMessage: 'Email is required'
        },

        'password': {
            notEmpty: true,
            errorMessage: 'Password is required'
        },

        'password_confirmation': {
            notEmpty: true,
            errorMessage: 'Password Confirmation is required'
        }

    });

    req.assert('password_confirmation', 'Passwords do not match').equals(req.body.password);

    req.check('username', 'This username is already taken').isUsernameAvailable();

    req.asyncValidationErrors().then(function() {
        next();
    }).catch(function(errors) {

        if(errors) {
            return res.json({
                success:false,
                errors: errors
            });
        };
    });
}
1reaction
Jakeiicommented, Feb 17, 2016

You’re using asyncValidationErrors() and validationErrors().

asyncValidationErrors() returns all errors async or not, no need to call validationErrors() as well.

On Tue, 16 Feb 2016 23:41 Julian Lasso notifications@github.com wrote:

Hi guys. Do you already able to solve the problem? I have also the same problem! 😦

— Reply to this email directly or view it on GitHub https://github.com/ctavan/express-validator/issues/199#issuecomment-184867243 .

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to create a custom async user-exists validator in Angular
This post will help you create a custom async validator that checks if a username is available working on the template-driven forms.
Read more >
angular - Validate Username Exist Async - Stack Overflow
Here is the example for you. A simple component initializes our reactive form and defines our async validator: validateEmailNotTaken.
Read more >
Username Availability with an Asynchronous Validator in ...
In this tutorial, I am going to focus on how to make a real request to a server for validation in an Angular...
Read more >
Using Custom Async Validators in Angular Reactive Forms
Our method to check if the username already exists is called checkIfUsernameExists . It returns an observable with a 5 seconds delay to...
Read more >
How to Add Async Validators to an Angular Reactive Form
It will contain a single form field called username. Then, whenever the user enters their username, we are going to check if it...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found