Vanilla JS

Tutorial of the basics: without framework

For this short tutorial, we will need the core package, as well as a theme:

npm install @phormal/core @phormal/theme-basic

We will create a form with four input fields. The paymentMethod radio group will be rendered with three different options. The name field will be a required field, and have a minimum length of 3 characters. The email field will also be required, and has to contain a valid email address. Lastly, there will be a checkbox for subscribing to a newsletter.

Step 1: JavaScript

import { Phormal, useEmail, useRequired, useLength } from '@phormal/core';
 
const formFields = {
  paymentMethod: {
    type: 'radiogroup',
    label: 'Payment Method',
    value: 'paypal',
    options: [
      {label: 'PayPal', value: 'paypal'},
      {label: 'Credit card', value: 'creditcard'},
      {label: 'Klarna', value: 'klarna'}
    ]
  },
  name: {
    label: 'Name',
    hooks: [useRequired(), useLength(3)]
  },
  email: {
    label: 'Email',
    hooks: [useRequired(), useEmail()]
  },
  newsletter: {
    type: 'checkbox',
    label: 'Newsletter',
    value: true
  },
}
 
const formConfig = { el: '#phormal', theme: 'basic' }
 
const form = new Phormal(formFields, formConfig)
// Access the input values:
// form.name = ''
// form.email = ''
// form.newsletter = true
// form.$values() = { name: '', email: '', newsletter: true }
// form.$validate() = false (false for form not yet being valid)
 

Step 2: HTML

In formConfig, we have specified the element, el, where the form should be rendered. Your HTML needs an element with the id phormal.

Step 3: CSS

The stylesheet for the basic theme is included in the @phormal/theme-basic package. You can import it such as:

@import '@phormal/theme-basic/dist/index.css'

Result


Last updated on January 21, 2023