Form

Create beautiful forms and validate them without the hassle.

Create a Form

With Gravity, you will never have to code another form again. Simply create an object with the form fields you need and pass it to the form component.

Your form will be automatically rendered and will perform its own validation and error handling.

Properties

  • data - the object containing your form fields (see below)
  • callback - function to be executed after a successful submit
  • url - url to send the form to
  • method - HTTP request type
  • redirect - url to redirect to after a successful submit
  • buttonText - submit button text
  • cancel - boolean to toggle a cancel button

Input Properties

When constructing a form object, the outer key is the input name and you pass an object with any combination of the following to configure the input properties.

  • label - the input label
  • type - text/number/url/phone/card/hidden/password/email/radio/checkbox/select/switch
  • placeholder
  • value - initial value
  • min - minimum value on number input
  • max - maximum value on number input
  • required - boolean
  • options - string array for radio and checkbox, object for select
  • default - default value for radio, select or checkbox
  • class - apply a custom class to the input
  • errorMessage - use a custom error message (overrride the default)

Example Form Object

formData = {
 name: {
  label: 'Your name',
  type: 'text',
  required: true,
  placeholder: 'Jon Smith',
  errorMessage: 'Please enter your name',
 },
 email: {
  label: 'Email address',
  type: 'email',
  required: true,
 },
 age: {
  label: 'Age',
  type: 'number',
  min: 18,
  max: 65,
 },
 phone: {
  label: 'Phone Number',
  type: 'phone',
  required: false
 },
 website: {
  label: 'Website',
  type: 'url',
  required: false,
 },
 gender: {
  label: 'Gender',
  type: 'radio',
  options: ['male', 'female'],
  required: true,
 },
 billingPlan: {
  label: 'Billing Plan',
  type: 'select',
  options: [
   { value: 'plan_startup', name: 'Startup' },
   { value: 'plan_enterprise', name: 'Enterprise' }
  ],
  default: 'plan_startup',
  required: true,
 } 
}

You can also nest multiple inputs in a single object if you need to use a group name when processing server-side.

Form Component

<Form
  data={ formObject }
  url='/api/demo'
  method='POST'
  redirect='/dashboard'
  buttonText='Save' />

When your form is submitted to the server, Gravity will optimise the request and only send the name/value pairs, so in Node.js you can access a value using:

req.body.email