Wednesday, 17 May 2017

Form validation using mongoose

My use case:

I am working on a signup page and I am sending an ajax request for the username to my server. The server should check if it is line with the validation rules (alphanumeric for example) and if the username is forgiven or free to use.

My idea:

I have defined validation rules on my mongoose model which. In order to avoid defining the exact same validation rules twice I wanted to use the mongoose schema to check against the validation rules and if the query passes then it should try to find the username in the db to check if it's still free.

The problem:

Unfortunately it seems like it doesn't check the validation for queries (instead it only does so before saving), hence I don't know how I could use the mongoose validation rules to validate the username input too.

My code:

checkSignUp:

function checkSignup(req, res, next) {
    var formField = req.params.field
    var expectedFormFields = ["username", "emailAddress", "password"]

    // Check if it's an expected field
    if(!expectedFormFields.includes(formField))
        res.status(403).send('Invalid request')

    if(formField == 'username') {
        var user = User.findOne({'local.username': req.body.value}, function (err, user) {
            if(err)
                res.status(403).send('Invalid request')

            if(user)
                res.status(409).send('Username is already forgiven')

            res.status(200).send()
        })
    }

    res.status(409).send('Unknown validation check, please contact a staff member')
}

My mongoose schema:

var userSchema = mongoose.Schema({
    local: {
        username: {
            type: String,
            required: [true, 'Empty usernames are not allowed'],
            validate: usernameValidator
        }});

The username validator:

var usernameValidator = [
    validate({
        validator: 'isLength',
        arguments: [3, 50],
        message: 'Userame should be between {ARGS[0]} and {ARGS[1]} characters'
    }),
    validate({
        validator: 'isAlphanumeric',
        passIfEmpty: false,
        message: 'Name should contain alpha-numeric characters only'
    })
]



via kentor

No comments:

Post a Comment