express-validator ignore invalidated fields

203 Views Asked by At

how can i ignore invalidated fields ?

i want just get all validated field in req.body

example:

POST : http://127.0.0.1:3000/api/auth/signup

{
    "name" : "Johen",
    "password" : "123456789",
    "confirm_password" : "123456789",
    "email" : "[email protected]",
    "role" : "admin" <-- i don't want this
}

checkSchema :

checking name,email and password

checkSchema({
    name: {
        isAlpha: {
            errorMessage: 'Your name must contain letters only',
        },
        isLength: {
            errorMessage: 'First name must be between 3 and 10 chars',
            options: {
                min: 3,
                max: 10,
            },
        },
    },
    email: {
        isEmail: {
            errorMessage: 'Email is not valid',
        },
        custom: {
            options: async (value, { req }) => {
                const user = await User.findOne({ where: { email: value } });
                if (user) throw new Error('Email already used');
                return true;
            },
        },
        normalizeEmail: [],
    },
    password: {
        notEmpty: {
            errorMessage: 'Choose a password for your account',
        },
        isLength: {
            errorMessage: 'Password must be between 6 and 30 chars',
            options: {
                min: 6,
                max: 30,
            },
        },
        custom: {
            options: (value, { req }) => {
                if (value !== req.body.confirm_password) throw new Error('Please confirm your password');
                return true;
            },
        },
    },
});

now in req.body i'm getting all fields

{
    "name" : "Johen",
    "password" : "123456789",
    "confirm_password" : "123456789",
    "email" : "[email protected]",
    "role" : "admin" <-- i don't want this
}

how can i prevent that ? i want req.body to contains onyl fields that i validated and ignore all others fields ?

i know i can use destructuring to extract fields that i want

const {name,email,password} = req.body;

but i don't want that.

i want to remove fields that doesn't exist in checkSchema

0

There are 0 best solutions below