vinejs / vine

VineJS is a form data validation library for Node.js
https://vinejs.dev
MIT License
1.1k stars 21 forks source link

feat: implement requiredIf rules #42

Closed thetutlage closed 8 months ago

thetutlage commented 8 months ago

The requiredIf rules offer an alternate API to the vine.union which is less type-safe but also simpler to write and express conditions.

Here's a quick example between the vine.union and the requiredIf rules.

With vine.union

const emailOrPhone = vine.group([
  vine.group.if((data) => 'email' in data, {
    email: vine.string().email()
  }),
  vine.group.if((data) => 'phone' in data, {
    phone: vine.string().mobile()
  }),
])

const loginForm = vine.object({
  password: vine
    .string()
    .minLength(6)
    .maxLength(32)
})
.merge(emailOrPhone)

The output type will be a union as well.

type LoginForm = {
  password: string
} & ({
  email: string
} | {
  phone: string
})

With requiredIfMissing

const loginForm = vine.object({
  email: vine.string().email().optional().requiredIfMissing('phone'),
  phone: vine.string().mobile().optional().requiredIfMissing('email'),
  password: vine
    .string()
    .minLength(6)
    .maxLength(32)
})

The output will have both email and phone as optional even though one of them will be defined at runtime.

type LoginForm = {
  email: string | undefined,
  phone: string | undefined,
  password: string
})

The requiredIfMissing rules are helpful when you do not care much about the output data-types and you do not want to narrow them. For example, validate data and store it as a JSON blob in the database

Julien-R44 commented 8 months ago

requiredIfExistsAny and requiredIfMissingAny sound weird to me. wouldn't requiredIfAnyExists and requiredIfAnyMissing be more appropriate?

maybe it's my English that's lacking here, so tell me if i am wrong

otherwise, looks perfect. cool and simpler alternative to unions 👌

thetutlage commented 8 months ago

requiredIfExistsAny and requiredIfMissingAny sound weird to me. wouldn't requiredIfAnyExists and requiredIfAnyMissing be more appropriate?

Yeah, your variation seems more natural to speak. Let's see if @RomainLanz thinks the same and then I can update the method names.

RomainLanz commented 8 months ago

I agree with @Julien-R44, requiredIfAnyExists and requiredIfAnyMissing sounds more natural. 👍🏻