𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗬𝗼𝘂𝗿 𝗢𝘄𝗻 𝗖𝘁𝗿𝗼𝗘𝗻𝘃 𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗼𝗿𝘀

The built-in validators in CtroEnv cover the basics. You get string, number, boolean, and pick. But sometimes you need more. I needed an IPv6 validator. It was not there. So I built it.

You can build your own validators using the same tools I use.

Here is how it works.

A validator is an object with a parse function and metadata. The parse function takes raw input and returns success or failure.

You can use createValidator to start. This is the simplest path.

However, a bare validator lacks helper methods. It does not have .default() or .optional(). You must use applyChain to add these methods.

If you want to add specific logic, like .min() for strings, you extend the validator. This allows you to wrap the original logic and add new rules.

There are two main ways to add custom logic:

Here is a summary of the tools you can use:

• createValidator: Create a base validator with custom logic. • applyChain: Add .optional(), .default(), and .describe(). • parseOk: Return a successful result. • singleError: Return a failed result. • errType and errInvalid: Create specific error messages.

You can even publish your own validators as community packages. Use the @ctroenv/community- prefix. Your package only needs @ctroenv/core as a dependency.

If you build something useful, please share it. You can open a PR or publish it for others to use.

Source: https://dev.to/ctrotech/building-your-own-ctroenv-validators-19h8