Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No Error when working with Arrays #105

Open
vinodKumarPula opened this issue Dec 12, 2019 · 1 comment
Open

No Error when working with Arrays #105

vinodKumarPula opened this issue Dec 12, 2019 · 1 comment

Comments

@vinodKumarPula
Copy link

var test= new Schema ({
test:[
{name:{type:String, required:true}}
]
})

Input:
test.validate({}) // throws no error
test.validate({vinod:{}}) // throws no error
test.validate({vinod:[]}) // throws no error
test.validate([]) // throws no error

I really like you library, but please give support for this It will be very helpful

Regards,
Vinod

@kareem-abdul
Copy link

kareem-abdul commented Feb 26, 2021

I know this is late but if anyone is facing this issue and needs a workaround you could use the custom validator to validate the array.

export const arrayValidator = (elementSchema: Schema) => {
    return (val: any[]) => {
        return val.every(element => {
            const errors: any[] = elementSchema.validate(element, { strip: false });
            if (errors && errors.length >= 1) {
                throw new Error(errors.map(error => error.message).join(", "));
                // I'm throwing the error here because since Im using nodejs with express 
                // I have an error handler that handles all the errors
                // By doing so I could get the custom validation messages in the elementSchema 
                // to my error handler
            }
            return true;
        });
    };
};


const studies = new Schema({
    label: { type: String, required: true }
});

const userSchema = new Schema({
    studies: {
        required: true,
        type: Array,
        use: { studiesValidator: arrayValidator(studies) } 
        // you might also want to add an empty array validator if required
    }
});

Then later validate using

let user = {
    studies: [{}]
}

const errors = userSchema.validate(user);
console.log(errors.map(error => error.message).join(", ")); // => label is required

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants