Search documentation v1.0.0

Form

Collect and submit user input

Source Report Issue

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.

Example Form
How to use the Form component in Astro
---
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>
You can find the documentation of the 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:

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:

Selecting forms using the useForm hook
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:

How to manipulate forms using the useForm hook
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
Note that the above methods can be chained, while 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:

How to access input fields using the hook
// Get the DOM element of the input whose name is set to "name"
form.getInput('name')
// Get the value of the "email" input
form.getInputValue('email')
// Get the value of all inputs
form.getInputValues()

Form Validation

The useForm hook can also be used for validation. The following example sets validations for each input whenever they change:

How to use form validations
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:

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'
}
Please see the documentation of each input type below to learn more about FormField configurations.
PropPurpose
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.
JavaScript API
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/MethodPurpose
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.
UseForm