Repository navigation
How to validate an object with keys that follow specific pattern (regex)? #1094
Replies: 2 comments 1 reply
|
Unfortunately, this harder then I wish because we do not support custom key schemas with import * as v from 'valibot';
const BaseSchema = v.object({
email: v.pipe(v.string(), v.email()),
password: v.pipe(v.string(), v.minLength(8)),
});
const ExtendedSchema = v.pipe(
v.objectWithRest(BaseSchema.entries, v.number()),
v.check((input) => {
for (const key in input) {
if (!(key in BaseSchema.entries) && !key.startsWith('field_')) {
return false;
}
}
return true;
}, 'Additional keys must be prefixed with "field_"'),
); |
|
To cover the extra-key case in your follow-up, import * as v from 'valibot';
const FieldValue = v.number();
const Schema = v.pipe(
v.looseObject({ foo: v.number(), bar: v.string() }),
v.rawCheck(({ dataset, addIssue }) => {
if (!dataset.typed) return;
for (const [key, value] of Object.entries(dataset.value)) {
if (key.startsWith('field_') && !v.is(FieldValue, value)) {
addIssue({
input: value,
message: 'Expected a number for this field_* property.',
path: [{
type: 'object',
origin: 'value',
input: dataset.value,
key,
value,
}],
});
}
}
})
);Your first example passes, including I checked this with Valibot 1.5.0, TypeScript 5.9.3 ( A few boundaries: this adds Docs: |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have object with a shape similar to one below:
How can I validate it using valibot?
I have known and static fields:
fooandbarI have dynamic fields following specific key pattern:
field_*, they all have the same type.There can be fields I don't care about at all, they won't be in the schema, I don't want them to result in failed validation, they should also work with
looseObjectbecause maybe they will be useful somewhere else.I tried playing with
recordandintersectbut this will fail because keys likeemailandpassworddon't match the regex here:It feels like it should be possible without hacks.
Thank you in advance!
All reactions