nuxt / ui

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
https://ui.nuxt.com
MIT License
3.62k stars 425 forks source link

Support form validation from OpenAPI schema definitions #1829

Open rigtigeEmil opened 1 month ago

rigtigeEmil commented 1 month ago

Description

Often times when working with api's, they'll expose an open api with validation rules. In combination with various generators, these can easily be extracted to typescript-generated validaiton files. For example https://heyapi.vercel.app/

It'd be super nice to avoid having to duplicate this already existing validation logic, and be able to use this directly as a form schema. I'm unsure if this is viable at all to support, since to my knowledge there's no standardized way to define these in ts or similar.

An example of the output from the above:

export const $ApiKeyCreateRequest = {
    required: ['name'],
    type: 'object',
    properties: {
        name: {
            minLength: 1,
            type: 'string'
        },
        permissions: {
            type: 'array',
            items: {
                '$ref': '#/components/schemas/ApiKeyBffPermission'
            }
        }
    },
    additionalProperties: false
} as const;

Additional context

No response

romhml commented 1 month ago

This seems a bit tricky to integrate reliably and meet everyone's needs, but I think you should be able to achieve this by extending the Form component and providing your own validation logic:

<script setup lang="ts">
const props = defineProps<{ schema: any }>() // Pass your OpenAPI schema as props

function validate(state: any) {
  // Validate your state using your OpenAPI schema or you validation file
  // Map the output as the as an Array of errors
  // `{ message: 'The error message', path: 'The name of the field' }` 
  // and return it
}
</script>

<template>
  <UForm :validate="validate">
    <slot />
  </UForm>
</template>

You can find more about this here: https://ui.nuxt.com/components/form#custom-validation.

github-actions[bot] commented 6 days ago

This issue is stale because it has been open for 30 days with no activity.