2

I want to validate if the input of a select element is in the array of valid values with Vue + Valibot.

I have a select with numeric values (IDs) and I need to check if is a valid ID.

So first I check if matches the numeric regex, and then I don't know how to add some validator for checking if the value is in the array.

import * as v from "valibot";

const validValues = ['1', '2', '4'];

const Schema = v.object({
  // ...
  user: v.string([v.regex(/^\d+$/)]),
});

Edit: I just saw the custom validator, and it worked doing:

  user: v.string([
    v.regex(/^\d+$/),
    v.custom((i) => validValues.includes(i), "not valid"),
  ]),

But there is some premade validator that achieves that?

1
  • 2
    Your solution is good. I don't think there's anything better than this. The best thing I could come up with is: ``` const validValues = ['1', '2', '4']; const schema = v.object({ user: v.union(validValues.map((value) => v.literal(value))), }); ``` Commented Apr 19, 2024 at 9:59

1 Answer 1

0

You can simply do it with v.check:

const validValues = ['1', '2', '4'];

const Schema = v.object({
  // ...
  user: v.array(
    v.pipe(
      v.string(),
      v.regex(/^\d+$/, 'Invalid ID format'),
      v.check((item) => validValues.includes(item), 'ID is not allowed')
    )
  )
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.