I am looking for a solution to provide different error messages in express-validator where the options can contain more than one value like isLength which can take min and max value.
var validation_rules = checkSchema({
first_name: {
notEmpty: {
errorMessage: 'The First Name field is required'
},
isString: {
errorMessage: 'The First Name must be a string.'
},
isLength: {
options: { min: 3, max: 4 }
}
}
});
As my example, I want to provide different error messages for min and max validation.
for min - The First Name must be at least 3 characters.
for max - The First Name may not be greater than 50 characters.
But I can only provide a single errorMessage here which is commonly used for both types of validation.
Can someone tell me how this can possible in express-validator checkSchema validation?
You can do it by creating a custom validator. In this custom validator check the length of your First-name with different conditions and for each invalid conditions reject with a promise your error message.
var validation_rules = checkSchema({
first_name: {
notEmpty: {
errorMessage: 'The First Name field is required'
},
isString: {
errorMessage: 'The First Name must be a string.'
},
custom: value => {
if (value.length < 3) {
return Promise.reject("The First Name is too short")
} else if (value.length > 4) {
return Promise.reject("The First Name is too long")
}
return Promise.resolve()
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With