Skip to main content

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 schema validation, we can easily validate the form and provide feedback to the user.

Basic Usage

Validation Schema

The validation schema is a 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.


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.

Object Validation

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>
);
}