Skip to content

Validate value based on key format #1159

@pgoerglerIaD

Description

@pgoerglerIaD

Hi,

How can I validate input based on the key name ?
If the key match /^foo(.+)$/ then it must be a string with maxLength 1
If the key match /^bar(.+)$/ then it must be a string with maxLength 10
otherwise no limitation
etc...

For example

{
  "foo(x)": "a",
  "bar(y)": "aaaaa",
  "z": "xxxxxxxxxxxxxxxx"
}

is valid
but this one is not

{
  "foo(x)": "aa"
}

because foo(x) must have 1 char max

I tried:

const FooSchema = v.record(v.pipe(v.string(), v.regex(/^foo\(.+\)$/)), v.pipe(v.string(), v.maxLength(1)))
const BarSchema = v.record(v.pipe(v.string(), v.regex(/^bar\(.+\)$/)), v.pipe(v.string(), v.maxLength(10)))
const WildcardSchema = v.record(v.string(), v.number())

const Schema = v.union([
  FooSchema,
  BarSchema,
  WildcardSchema,
])

const result = v.safeParse(Schema, {
  'bar(a)': 'x',
  'foo(b)': 'xxxxxx',
  'z': 'xxxxxxxxxxxxxxxx'
});

It does not work it returns

Invalid format: Expected /^foo\(.+\)$/ but received "bar(a)"
and more

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requeststaleIssue has not had recent activity or appears to be solved. Stale issues will be automatically closedworkaroundWorkaround fixes problem

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions