0

JOI 10 is used to validate calls against an API. I now want to sanitize many (but not all) of the strings that are contained in the JSONs before validating them, namely filter out certain characters. I know that this would be an easy task with a recent JOI version as there's the custom() method that I could use. Unfortunately updating JOI is not an option and so I am currently looking for an elegant way to solve this, preferably using the JOI schemas.

I found that there is the extend() function which allows me to define custom types/validations. However, I am not entirely sure how to use it and where to put the code. Also, I am not sure if it's suited to alter the string at all. Can I use extend() to achieve this? If not, is there another way to do this within JOI?

gizarmaluke
  • 55
  • 1
  • 6

1 Answers1

1

OK, it's actually pretty easy.

const customJOI = JOI.extend({
    name: "sanitizedString",
    base: JOI.string(),
    pre(value: string, state: any, options: any) {
        return value.replace(/yourregex/, "");
    }
});

and just use customJOI instead of JOI where the sanitization is needed with .sanitizedString() instead of .string().

gizarmaluke
  • 55
  • 1
  • 6