async-validator icon indicating copy to clipboard operation
async-validator copied to clipboard

Feature Request: Optional rules

Open brendan-lee opened this issue 4 years ago • 0 comments

It would be convenient if a rule could be defined as optional.

Use cases

Case 1

const data1 = { text: '' }
const data2 = { text: 'short' }
const data3 = { text: 'loooooong' }

const descriptor = {
  text: [
    { required: false, when: ({ value }) => value.length === 0 },
    { required: true, min: 6, when: ({ value }) => value.length > 0 }
  ]
}

const validator = new Schema(descriptor)

validator.validate(data1) // pass
validator.validate(data2) // fail
validator.validate(data3) // pass

Case 2

const user1 = {
  type: 'id',
  value: 123
}

const user2 = {
  type: 'name',
  value: 'Tom'
}

const user3 = {
  type: 'id',
  value: 'Jerry'
}

const descriptor = {
  type: { required: true },
  value: [
    { type: 'number', when: ({ source }) => source.type === 'id' },
    { type: 'string', when: ({ source }) => source.type === 'name' }
  ]
}

const validator = new Schema(descriptor)

validator.validate(user1) // pass
validator.validate(user2) // pass
validator.validate(user3) // fail

Ref

#32, #42, #82, #210, #255

brendan-lee avatar Jan 07 '21 13:01 brendan-lee