You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello, So I am working in a large project and I'm tired of writing the same validator code everytime so i created a few functions which will return the validation logic when i call them and i can re-use them wherever i want.
For example, suppose this is my function :
const stringValidate = (source, text, optional) => {
switch (source) {
case "body":
if (optional) {
return body(text)
.optional()
.isString()
.withMessage(`${text} must be String`)
.trim();
}
let val = body(text)
.notEmpty()
.withMessage(`${text} Required`)
.bail()
.isString()
.withMessage(`${text} must be String`)
.trim();
console.log("val", val);
return val;
case "query":
if (optional) {
return query(text)
.optional()
.isString()
.withMessage(`${text} must be String`)
.trim();
}
return query(text)
.notEmpty()
.withMessage(`${text} Required`)
.bail()
.isString()
.withMessage(`${text} must be String`)
.trim();
case "param":
if (optional) {
return param(text)
.optional()
.isString()
.withMessage(`${text} must be String`)
.trim();
}
return param(text)
.notEmpty()
.withMessage(`${text} Required`)
.bail()
.isString()
.withMessage(`${text} must be String`)
.trim();
default:
console.log(`Default validator case for ${text} in ${source}`);
}
};
This function will return a validation logic for any string based validation. The function takes 3 arguments :
Source : source is either body, query or param
Text : The name of the field
Optional : Boolean, true if field is optional and vice-versa.
And this function I am trying to use in a route call like this
Hi,
I'm not sure where your message is originating from. Most likely not from express-validator. Can you create a small reproduction repository?
On another note, you can make use of buildCheckFunction to make your function way smaller.
conststringValidate=(source,text,optional)=>{constvalidateFn=buildCheckFunction([source]);constchain=validateFn(text);if(optional){chain.optional();}else{chain.notEmpty().withMessage(`${text} required`).bail();}returnchain.isString().withMessage(`${text} must be String`).trim();};
Hello, So I am working in a large project and I'm tired of writing the same validator code everytime so i created a few functions which will return the validation logic when i call them and i can re-use them wherever i want.
For example, suppose this is my function :
This function will return a validation logic for any string based validation. The function takes 3 arguments :
And this function I am trying to use in a route call like this
But the above code gives me an error
So My question is if its possible what I am trying to do? Or do i have to look for a different method
The text was updated successfully, but these errors were encountered: