Form
Collect and submit user input
Use the Form
component to collect and submit user input. You can use the Form
component to build forms, including but not limited to authentication (such as login, register, or password reset), submission (such as orders or feedback), or contact forms.
---const fields = [ { type: 'text', label: 'Name', name: 'name' }, { type: 'email', label: 'Email', name: 'email' }, { type: 'checkbox', label: 'I accept the <a>terms and conditions</a>', name: 'terms' }, { type: 'button', label: 'Subscribe' }]---
<Form fields={fields} id="form" />
<script> import { toast } from 'webcoreui' import { useForm } from '@blocks/Form/useForm'
const form = useForm('#form')
if (form) { form.preventDefault() .update('name', 'John Doe') .update('email', 'john@doe.com') .onChange(formValues => { console.log('form values changed to:', formValues) }) .onSubmit(form => { toast({ element: '#toast', content: `Submitting form with values: ${JSON.stringify(form)}`, timeout: 3000 })
console.log('Submitting form with values:', form) }) .onError(form => { toast({ element: '#toast', content: `Error submitting form. Invalid fields: ${JSON.stringify(form)}`, timeout: 3000 })
console.log('Error submitting form. Invalid fields:', form) }) }</script>
Toast
component here to learn more about how to work with toasts. The above example form can be used for collecting names and emails from users. To create a form, pass a fields
prop to the component that specifies the input fields. Each field must have the following two properties:
type
: The type of the input, which can be a valid input type, including the following custom types:slider
: Renders a range slider.switch
: Renders a switch toggle that acts as a checkbox.textarea
: Renders a textarea for multiline text input.
name
: The name of the input that can be used for referencing the field during validation, change events, submission, and error reporting.
Fields objects can be configured with additional properties. Each input type accepts different types of properties. For a complete list of documentation, please refer to the page of the individual input types:
You can specify the action
prop to use the form as-is, or you can use the custom useForm
hook provided with the form to handle submissions on the client.
useForm Hook
The Form
component comes with a useForm
hook that you can use to manipulate the form and listen to form events. To use the hook, call useForm
with a selector that selects the form that you want to use. In the above example, we used the id
of the form:
const form = useForm('#form') // Select the form with the id of "form"
From here, you can attach various methods on the form
variable to manipulate the form and its inputs. For example:
form.preventDefault() // Prevent default form behavior .update('name', 'John Doe') // Update input fields with key-value pairs .onChange(formValues => { ... }) // Attach onChange event listeners .onSubmit(form => { ... }) // Listen to events when the form is submitted .onError(form => { ... }) // Listen to errors when a validation error occurs
getInput
, getInputValue
or getInputValues
cannot be chained. Accessing Input Fields
To access the value of input fields or the input fields themselves, you can use the following methods on the form:
// Get the DOM element of the input whose name is set to "name"form.getInput('name')
// Get the value of the "email" inputform.getInputValue('email')
// Get the value of all inputsform.getInputValues()
Form Validation
The useForm
hook can also be used for validation. The following example sets validations for each input whenever they change:
form.preventDefault() .onChange(formValues => { const validationRules = { email: !!formValues.email.includes('gmail'), message: !!(formValues.message?.length > 20) }
form.setValidations(validationRules) }) .onSubmit(form => { console.log('Submitting form with values:', form) })
The setValidations
method expects a validation object where keys reference the input field’s name, and values are either true
or false
depending on their validity. The above rules expects that:
email
: The email input should include “gmail”.message
: The message field should be at least 20 characters long.
API
type FormField = | ({ type: 'button', label: string } & ButtonProps) | ({ type: 'checkbox' } & CheckboxProps) | ({ type: 'radio' } & RadioProps) | ({ type: 'select' } & SelectProps) | ({ type: 'slider' } & SliderProps) | ({ type: 'switch' } & SwitchProps) | ({ type: 'textarea' } & TextareaProps) | ({ type: InputProps['type'] } & Omit<InputProps, 'type'>)
type FormProps = { fields: FormField[] gap?: Gap className?: string id?: string name?: string action?: string method?: 'post' | 'get' | 'dialog' noValidate?: boolean target?: | '_self' | '_blank' | '_parent' | '_top' | '_unfencedTop' enctype?: | 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain'}
FormField
configurations. Prop | Purpose |
---|---|
fields | Sets the input fields for the form. |
gap | Sets the gap between the input fields. |
className | Sets a class for the form. |
id | Sets an id for the form. |
name | Sets the name attribute on the form. |
action | Sets the action attribute on the form. |
method | Sets the method attribute on the form. |
noValidate | Sets the form to noValidate . |
target | Sets the target attribute on the form. |
enctype | Sets the enctype attribute on the form. |
type FormActions = { validationRules: Record<string, boolean> isPreventDefault: boolean onErrorCallback: ((invalidFields: string[]) => void) | null preventDefault: () => FormActions getInput: (field: string) => HTMLInputElement | null getInputValue: (field: string) => string | null getInputValues: () => Record<string, string> update: (field: string, value: string) => FormActions setValidations: (validationRules: Record<string, boolean>) => FormActions isValidForm: () => boolean, onChange: (callback: (formValues: Record<string, string>) => void) => FormActions onSubmit: (callback: (formValues: Record<string, string>) => void) => FormActions onError: (callback: (invalidFields: string[]) => void) => FormActions}
Property/Method | Purpose |
---|---|
validationRules | Returns the validation object set by setValidations . |
isPreventDefault | Returns a boolean whether the preventDefault is set for the form. |
onErrorCallback | Returns the callback function specified by onError . |
preventDefault() | Calling the method sets preventDefault to true . |
getInput() | Pass the name of the input to return the DOM element for the input field. |
getInputValue() | Pass the name of the input to return its value. |
getInputValues() | Returns the values of all input fields from the form. |
update() | Sets a value for the specified input field. |
setValidations() | Sets a list of input validations that prevents the form from submission with invalid fields. |
isValidForm() | Returns a boolean indicating whether the form is valid based on the set validation rules. |
onChange() | Attach event listener to the form that triggers when any of its inputs change. |
onSubmit() | Attach event listener to the form that triggers when the form is submitted. |
onError() | Attach event listener to the form when an error occurs due to validation. |