Search code examples
expressexpress-validator

How can I validate a nested POST body payload with the checkSchema middleware in express-validator?


Given the following sample POST body:

User = {
    email: string; //required, email
    password: string; //required, min length 8

    profile: {
        firstName: string;  //required
        lastName: string;   //required
        gender: Gender;     //required, enum (M/F)
    }
}

How can I define an express ValidationSchema to validate the nested Profile object and its props inside the User

userValidatorSchema: ValidationSchema = {
    email: {
        isEmail: {}
    },
    password: {
        exists: {
            options: {checkNull: true},
            errorMessage: 'Null value'
        },
        isEmpty: {
            negated: true,
            errorMessage: 'Empty string'
        }        
    }
    //Profile validation??

Express-validator docs make it look like this is not possible with express-validator. If so, what is a more versatile validator for express?


Solution

  • Have you tried this approach:

    // Profile validation
    profile: {
      optional: false
    },
    'profile.firstName': {
      notEmpty: true,
      optional: false
    }
    // ...others