Use with Nuxt UI

How to integrate Pracognition into Nuxt UI forms.

Since Nuxt UI Form uses its own validation process, there is no way to integrate it with the Precognition protocol directly. However, we can define custom validation by passing a function as a form option.

This module provides a special composable - useNuxtFormValidator, which returns a validator function compatible with Nuxt UI Form.

Here is an example of using Nuxt UI Form along with Precognition validation:

MyForm.vue
<script setup lang="ts">
type LoginForm = {
  email: string
  password: string
  remember_me?: boolean
}

const payload: LoginForm = {
  email: '',
  password: '',
  remember_me: false,
}

const form = usePrecognitionForm<LoginForm>('post', '/login', payload)
const validator = useNuxtFormValidator(form)
const state: LoginForm = form.fields

async function onSubmit(_: FormSubmitEvent<LoginForm>) {
  try {
    const response = await form.submit()
  }
  catch {
    console.error('Form submission error')
  }
}
</script>

<template>
  <UForm
    :validate="validator"
    :state="state"
    @submit="onSubmit"
  >
    <UFormField
      label="Email"
      name="email"
    >
      <UInput
        v-model="state.email"
        placeholder="Email"
      />
    </UFormField>

    <UFormField
      label="Password"
      name="password"
    >
      <UInput
        v-model="state.password"
        placeholder="Password"
        type="password"
      />
    </UFormField>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

While using Nuxt UI Form, validation of the fields is triggered automatically according to the form's settings.

Last updated