Joi Validation Regex or pattern
17,163
Solution 1
If you want to use pattern as variable, just pass it:
module.exports = (pattern) => ({
save: {
body: {
match: Joi.string().regex(pattern).required
}
}
});
And use it like:
const pattern = "/^[0-9+]{7}-[0-9+]{1}$/";
validator(pattern)
Solution 2
module.exports = (exp) => ({
save: {
body: {
match: Joi.string().pattern(new RegExp(exp)).required()
}
}
});
Related videos on Youtube
Author by
Imran Rafiq
Updated on June 04, 2022Comments
-
Imran Rafiq almost 2 years
I want to joi use regex pattern which define in variable
I have a variable pattern which contains regex i.e
pattern = "/^[0-9+]{7}-[0-9+]{1}$/"
and this pattern send to Joi module and want to confirm
module.exports = { save: { body: { match: Joi.string().regex(pattern).required } } }
I know validation work if I use this
module.exports = { save: { body: { match: Joi.string().regex(/^[0-9+]{7}-[0-9+]{1}$/).required } } }
But in my case every time regex will different. So I can not use above regex pattern
-
BDL about 4 yearsAlthough this code might solve the problem, a good answer should also explain what the code does and how it helps.