How do I apply custom validation rules to a FormKit schema?

206 views Asked by At

I'm trying to apply custom validation rules using a FormKit schema. I can get the normal formkit component to work without any trouble. However when trying with a FormKit schema it doesn't work.

Here's an example: https://formkit.link/28c461b2b93f6d2c50d23debc37c276b

Thanks in advance.

You can see on the link provided what im trying to achieve.

1

There are 1 answers

0
Garbit On BEST ANSWER

If you're using FormKit schema to define your inputs you need to pass the custom validation rules into the schema element using the :data binding attribute on your FormKitSchema element.

FormKit playground: https://formkit.link/10d9045f7cf8510fbc7ac0c26895f02d

For example:

<script setup>
function day(node, group = 'weekdays') {
  const dayNames = [
    'monday',
    'mon',
    'tuesday',
    'tue',
    'wednesday',
    'wed',
    'thursday',
    'thu',
    'friday',
    'fri',
    'saturday',
    'sat',
    'sunday',
    'sun',
  ]
  const value = node.value.toLowerCase()
  switch (group) {
    case 'weekdays':
      return dayNames.slice(0, 10).includes(value)
    case 'weekend':
      return dayNames.slice(10).includes(value)
    default:
      return dayNames.includes(value).includes(value)
  }
}

const schema = {
  $formkit: 'text',
  label: 'Weekend day',
  validation: 'day:weekend',
  validationRules: '$validationRules',
  validationVisibility: 'live',
  help: 'Enter a weekend day.'
};

const data = {
  validationRules: { day }
}
</script>

<template>
  <FormKitSchema :schema="schema" :data="data" />
</template>