import { FormExamples, MDXLayoutNext } from '@/components';

export const meta = {
  templateTitle: 'Validation',
  description: 'Form | Fluid Design',
  date: '2023-02-01',
  author: 'Oliver Pan',
  tags: [
    'fluid ui',
    'react',
    'framer motion',
    'headless ui',
    'tailwindcss',
    'form',
    'validation',
  ],
};

export default (props) => (
  <MDXLayoutNext meta={meta} components={FormExamples} {...props} />
);

# Validation

Validation is a very important part of any form.
It helps to ensure that the user is entering the correct information and that the form is filled out correctly.
It also helps to ensure that the form is filled out completely.
By using [yup](https://www.npmjs.com/package/yup) schema validation, we can easily validate the form and provide
feedback to the user.

<CodeFrame title='Basic Usage'>
  <Validation.Basic />
</CodeFrame>

## Validation Schema

The validation schema is a [yup](https://www.npmjs.com/package/yup) schema that is used to validate the form.
The schema is passed to the `validationSchema` prop of the `Form` component.

> The submit button will be disabled if the form is invalid.

```jsx
import { Form, Input, SubmitButton, Textarea } from '@fluid-design/fluid-ui';
import * as Yup from 'yup';

function Example() {
  const validationSchema = Yup.object().shape({
    firstName: Yup.string()
      .min(2, 'Too Short!')
      .max(50, 'Too Long!')
      .required('First Name is required'),
    email: Yup.string()
      .min(3, 'Must be at least 3 characters long')
      .email('Invalid email')
      .required('Email is required'),
    message: Yup.string(),
  });
  return (
    <Form
      onSubmit={() => null}
      initialValues={{
        firstName: '',
      }}
      validationSchema={validationSchema}
    >
      <Input label='First Name' name='firstName' type='text' />
      <Input label='Email' name='email' type='email' />
      <Textarea label='Message' name='message' />
      <SubmitButton label='Submit' />
    </Form>
  );
}
```

## Object Validation

You can also use objects or arrays in your validation schema.

<CodeFrame title='Object Validation'>
  <Validation.ObjectValues />
</CodeFrame>

```jsx
import { Form, Select } from '@fluid-design/fluid-ui';

function Example() {
  const validationSchema = Yup.object().shape({
    food: Yup.array()
      .min(1, 'You must select at least one food')
      .max(4, 'You can only select up to 4 foods'),
  });

  return (
    <CodeFrameComponentWrap className={defaultFormClassName}>
      <Form
        onSubmit={() => null}
        initialValues={{
          food: [],
        }}
        validationSchema={validationSchema}
      >
        <Select
          name='food'
          itemKey='name'
          disabledKey='unavailable'
          list={food}
          label='Food'
          placeholder='Select food'
          //multiple={4} // max 4
          multiple // unlimited
        />
      </Form>
    </CodeFrameComponentWrap>
  );
}
```
