GitHub v1.3.1

formControl

Stable

Opt-in integration with native HTML <form> submissions and constraint validations.

TypeScript Signature

typescript
Code copied!
  // Opt-in by exporting a boolean
  export const formControl: boolean = true

Native Form Association

Because Coralite uses Light DOM, your custom elements can participate in standard HTML forms. By exporting export const formControl = true, Coralite attaches an ElementInternals object to the custom element, making it a true Form-Associated Custom Element (FACE).

The Form Hooks

When formControl is enabled, the client() context receives additional helpers to synchronize your component's state with the form.

javascript
Code copied!
  export async function client ({
    state,
    refs,
    setFormValue,
    setValidity,
    onFormReset,
    onFormDisabled,
    onFormRestore,
    signal
  }) {
    // Sync initial state
    setFormValue(state.value)
  
    // Bind input
    refs('input').addEventListener('input', (e) => {
      state.value = e.target.value
      setFormValue(state.value)
    }, { signal })
  
    // Handle form reset
    onFormReset(() => {
      state.value = ''
      refs('input').value = ''
    })
  }

Constraint Validation

You can use setValidity to integrate your component with the browser's native validation UI (e.g., the red outline or tooltip).

javascript
Code copied!
  setValidity(
    { valueMissing: true }, 
    'This field is required.', 
    refs('input') // The anchor element for the browser tooltip
  )

Complete Example

Here is how a custom input component wires up the full FACE lifecycle.

html
Code copied!
  <template id="custom-input">
    <input ref="input" type="text">
  </template>
  
  <script type="module">
    export const formControl = true
    export const attributes = { value: { type: String, default: '' } }
  
    export function client ({ state, refs, setFormValue, onFormReset, signal }) {
      const input = refs('input')
      setFormValue(state.value)
  
      input.addEventListener('input', (e) => {
        state.value = e.target.value
        setFormValue(state.value)
      }, { signal })
  
      onFormReset(() => {
        state.value = ''
        input.value = ''
      })
    }
  </script>