Skip to content

Add support for custom nanoid sizes #3954

Open
@Jodenee

Description

Problem

Nanoids can vary in length, while they are mainly 21 characters in length some may be larger. For example the npm package 'nanoid' allows developers to generate ids at any length so it would be nice to have that built into zod.

Ideal solution

const goodNanoid = "MJBTltG6zIHelSq42cz51j_lESP7YSD_lLoOG4y_hsikIfCI403gLw6oJnreQW7u"
const badNanoid = "xv02pdYYi8Tb1SF1WjfSe" // bad because the nanoid's length is expected to be 64 characters
const schema = z.string().nanoid(64)

const goodNanoidResult = schema.safeParseAsync(goodNanoid)
const badNanoidResult = schema.safeParseAsync(badNanoid)

console.log(goodNanoidResult.success) // should be true
console.log(badNanoidResult.success) // should be false

Work around

const goodNanoid = "MJBTltG6zIHelSq42cz51j_lESP7YSD_lLoOG4y_hsikIfCI403gLw6oJnreQW7u"
const badNanoid = "xv02pdYYi8Tb1SF1WjfSe" // bad because the nanoid's length is expected to be 64 characters
// regex taken from https://github.com/colinhacks/zod/blob/f7ad26147ba291cb3fb257545972a8e00e767470/src/types.ts#L643C21-L643C40
const schema = z.string().regex(/^[a-z0-9_-]{64}$/i) // if you wish to check for a higher or lower size nanoid just change the 64 with the size of your choice

const goodNanoidResult = schema.safeParseAsync(goodNanoid)
const badNanoidResult = schema.safeParseAsync(badNanoid)

console.log(goodNanoidResult.success) // true
console.log(badNanoidResult.success) // false

If anymore information is needed please let me know.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions