Pass an other data with value to validation function.
The following will be code for maxlength validation
maxLength = function (v) {
if (v && v.length) {
return v.length <= 100;
}
},
The schema field
desc: { type: String, validate: [maxLength, 'Exceed max length of 100 chars'] }
Can we pass a data with validate?
i.e Like below code
desc: { type: String, validate: [maxLength, 100, 'Exceed max length of 100 chars'] }
maxLength = function (v, length) {
if (v && v.length) {
return v.length <= length; // length will be 100
}
},
Here validate second array element(length of desc
) is passed to validation function. Later validate with this passed length.
How it can be accomplished?
What is the use case?
@aheckmann I need a maximum length(maxlength) validator for String fields in schema. Each string fields have different maxlengths. So I need a common validator for maxlength with length of string need to be passed to validation function. So that I can control maxlength of different string fields from common validation function, not by writing different validation function for each String fields in schema.
I think the best way to do this might be to just have a function which constructs your validator.
IE.
function getMaxValidator(val) {
return function (v) {
if (v && v.length) {
return v.length <= val;
}
}
}
// To get a validator for length 100, you'd do something like this
...
validate : getMaxValidator(100),
...
Pretty sure this should cover your use case here. If this doesn't work for you, let me know and we can reopen this.
@ebensing How we can trigger the custom error message Exceed max length of 100 chars
here?
See the docs for how to pass custom error messages to validation functions.
Most helpful comment
I think the best way to do this might be to just have a function which constructs your validator.
IE.
Pretty sure this should cover your use case here. If this doesn't work for you, let me know and we can reopen this.