menu_book Navigation menu

Form Validator & API

Overview

Pragma CMS automatically takes over any <form> element containing the attribute data-cms-form="true". This core module handles native HTML5 validation, ARIA accessibility, file size/type restrictions, conditional logic, and AJAX submissions.

The module is exposed globally under window.CMS.forms.

The Validator Object

The Validator handles UI error states, ensuring that error messages are properly linked to inputs via aria-describedby for screen readers.

Validator.setError()

Highlights an input field in red and displays an error message below it (or inside the <fieldset> for radio/checkbox groups).

Signature:

JAVASCRIPT
window.CMS.forms.Validator.setError(elem, message)

Validator.clearError()

Removes error classes, hides error messages, and removes aria-invalid attributes from a specific input.

Signature:

JAVASCRIPT
window.CMS.forms.Validator.clearError(elem)

Validator.validateField()

Manually triggers the CMS validation rules on a specific field. It evaluates required attributes, email regex, select dropdowns, and file arrays.

Signature:

JAVASCRIPT
const result = window.CMS.forms.Validator.validateField(elem, selectedFilesGetter);
// Returns: { valid: boolean, message: string | null }

The FileManager Object

Because standard HTML <input type="file"> elements lose their data if the user selects files multiple times, Pragma CMS uses a virtual FileManager to accumulate files in memory before submission.

  • FileManager.getFilesForInput(input): Returns the array of File objects currently held in memory for a specific input.
  • FileManager.clearForForm(form): Empties the virtual memory when the form resets.

Custom Events (Hooks)

The form engine dispatches native DOM Custom Events, allowing you to execute custom logic without hacking the core script.

Event Nameevent.detail payloadDescription
cms:form:submitted{ form, formData }Fired right before the AJAX request is sent. You can append data to formData here.
cms:form:success{ form, result }Fired when the server returns success: true.
cms:form:error{ form, error, result }Fired when the server returns an error or a network failure occurs.
cms:forms:reinit(None)Listen for this globally. Trigger this to force the CMS to re-scan the DOM for new forms (useful after injecting HTML via AJAX).

Example: Intercepting a form submission

JAVASCRIPT
document.addEventListener('cms:form:submitted', (e) => {
    const { form, formData } = e.detail;
    
    if (form.id === 'tracking-form') {
        formData.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
    }
});