quantique-forms
v2.0.0
Published
JSON-driven dynamic form engine for React — 17 field types, validation via quantique-field-validator, CSS-variable theming
Maintainers
Readme
quantique-forms
JSON-driven dynamic form engine for React.
Describe your entire form as a plain JavaScript/TypeScript object.DynamicFormrenders the correct field, applies smart input filters, wires up validation, and hands you a clean typed object on submit — no hand-rolled JSX, no per-field boilerplate.
Table of contents
- What is this?
- Why use it?
- Installation
- Quick start — 60 seconds
- All 23 field types with examples
- Smart field-type constraints
- Override auto-constraints
- Full ValidationConfig reference
- Date validation rules
- Sections — grouping fields visually
- Theming and styling
- Inter-field reactivity
- Pre-filling default values
- Custom submit / action buttons
- DynamicForm prop reference
- FieldConfig full reference
- TypeScript types
- Real-world example — vehicle registration form
- Advanced usage
- Accessibility
- Changelog
1. What is this?
Most React forms require you to write the same boilerplate over and over — one block of JSX per field, with manual label, input, error, register, pattern, and accessibility wiring:
// WITHOUT quantique-forms — you write this for EVERY field
<div>
<label htmlFor="pan">PAN Card *</label>
<input
id="pan"
maxLength={10}
onChange={(e) => setValue('pan', e.target.value.toUpperCase())}
{...register('pan', {
required: 'PAN is required',
pattern: { value: /^[A-Z]{5}[0-9]{4}[A-Z]$/, message: 'Invalid PAN' },
})}
/>
{errors.pan && <span className="error">{errors.pan.message}</span>}
</div>With quantique-forms, you write a plain object instead:
// WITH quantique-forms — describe what you want, library handles the rest
{
id: 1,
title: 'PAN Card',
variableName: 'pan',
type: 'textField',
placeholder: 'ABCPE1234F',
validations: {
isRequired: true,
fieldType: 'pan', // ← auto-uppercase, max 10, alphanumeric only, format check
},
}That one object produces: a labelled input, auto-uppercasing on every keystroke, character filter (alphanumeric only), hard max-length cap, PAN format validation, required check, and an inline error message — all styled consistently.
2. Why use it?
| Challenge | Without this library | With quantique-forms |
|---|---|---|
| Building a form with 10 fields | ~300 lines of JSX + hooks | ~50 lines of JSON |
| Adding a new field | Edit JSX, register, add error UI | Add one object to the array |
| Form from an API / CMS / DB | Complex mapping code | Pass the JSON array directly |
| Theming all 23 field types consistently | Override CSS in 20+ places | Change one CSS variable |
| Indian field validation (PAN, GST, IFSC, Aadhaar…) | Write/test regex by hand | Set fieldType: 'pan' |
| Smart input (digits-only, uppercase, numeric keyboard) | Custom onChange per field | Automatic via fieldType |
| Vehicle form (chassis, engine, reg code, policy no.) | Research each format separately | Built-in field types |
| Prevent invalid characters from being typed | Custom onKeyDown filter per field | Automatic via fieldType |
3. Installation
npm install quantique-forms
# or
yarn add quantique-forms
# or
pnpm add quantique-formsPeer dependencies (install if not already in your project):
npm install react react-dom
react-hook-formandquantique-field-validatorship as dependencies insidequantique-forms— you do not need to install them separately unless you use them directly.
Node.js ≥ 18, React ≥ 18, TypeScript 5.x (optional)
4. Quick start — 60 seconds
Step 1 — Import the stylesheet once (at the very top of your app)
// main.tsx OR App.tsx OR layout.tsx — wherever your app starts
import 'quantique-forms/styles';You only need this once per application. If you skip this, the fields will render without any styling.
Step 2 — Describe your fields and render DynamicForm
import { DynamicForm } from 'quantique-forms';
import type { FieldConfig } from 'quantique-forms';
const fields: FieldConfig[] = [
{
id: 1,
title: 'Full Name',
variableName: 'fullName',
type: 'textField',
placeholder: 'Jane Smith',
validations: { isRequired: true, minLength: 2, maxLength: 80 },
},
{
id: 2,
title: 'Email Address',
variableName: 'email',
type: 'email',
placeholder: '[email protected]',
validations: {
isRequired: true,
fieldType: 'email',
errorMessages: { invalid: 'Please enter a valid email address.' },
},
},
{
id: 3,
title: 'Role',
variableName: 'role',
type: 'dropdown',
placeholder: 'Select a role…',
options: [
{ value: 'admin', label: 'Admin' },
{ value: 'editor', label: 'Editor' },
{ value: 'viewer', label: 'Viewer' },
],
validations: { isRequired: true },
},
];
export default function MyForm() {
return (
<DynamicForm
fields={fields}
onSubmit={(data) => console.log(data)}
// Logs: { fullName: 'Jane Smith', email: '[email protected]', role: 'editor' }
renderActions={(isSubmitting) => (
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving…' : 'Save'}
</button>
)}
/>
);
}What happens automatically:
- The form validates on submit
- Required field errors appear inline
- Email format is checked
onSubmitis only called when every field passes validation- The submitted
dataobject keys match each field'svariableName
5. All 23 field types with examples
Every field config needs at minimum: id, title, variableName, and type. Everything else is optional.
textField
A standard single-line text input. The most versatile field type — works for names, addresses, reference codes, ID numbers, and anything else. Pair it with fieldType in validations to get smart constraints.
{
id: 1,
title: 'Full Name',
variableName: 'fullName',
type: 'textField',
placeholder: 'Jane Smith',
info: 'Enter your legal name as it appears on your government ID.',
validations: {
isRequired: true,
isRequiredError: 'Please enter your full name.',
minLength: 2,
maxLength: 80,
minLengthError: 'Name must be at least 2 characters.',
maxLengthError: 'Name cannot exceed 80 characters.',
},
}What the user sees: A labelled text box. Required fields show a red *. An optional info string appears below the label as a hint. Validation errors appear below the input after the user blurs or submits.
email
A text input with type="email". On mobile, this shows the email-optimised keyboard (with @ key visible). Use fieldType: 'email' to add format validation.
{
id: 2,
title: 'Email Address',
variableName: 'email',
type: 'email',
placeholder: '[email protected]',
validations: {
isRequired: true,
fieldType: 'email',
errorMessages: {
required: 'Email address is required.',
invalid: 'Please enter a valid email (e.g. [email protected]).',
},
},
}password
A password input with a built-in show/hide eye icon. The user can click the eye to reveal what they typed. Pair with fieldType: 'password' and minLength for strength enforcement.
{
id: 3,
title: 'Password',
variableName: 'password',
type: 'password',
placeholder: 'Min 8 characters',
validations: {
isRequired: true,
minLength: 8,
fieldType: 'password',
errorMessages: {
required: 'Please create a password.',
invalid: 'Password must contain at least one letter and one number.',
},
},
}multiTextField (textarea)
A resizable multi-line text area. Control its default height using rowSize. Ideal for comments, notes, addresses, and longer free-form text.
{
id: 4,
title: 'Additional Notes',
variableName: 'notes',
type: 'multiTextField',
placeholder: 'Enter any additional information…',
rowSize: 5,
validations: { maxLength: 500 },
}rowSize — number of visible text rows (height). Default is 3. Set higher for longer content (e.g. rowSize: 8 for a full description field).
A live character counter (0 / 500) appears in the bottom-right corner when maxLength is set.
numberField
An integer (whole number) input. Digits only — no decimals, no letters. On mobile, shows the numeric keyboard. Supports min/max value checks.
{
id: 5,
title: 'Age',
variableName: 'age',
type: 'numberField',
placeholder: '25',
validations: {
isRequired: true,
minValue: 18,
maxValue: 120,
minValueError: 'You must be at least 18 years old.',
maxValueError: 'Please enter a valid age (18–120).',
},
}minValue / maxValue — checked on submit. A value of 150 with maxValue: 120 shows maxValueError.
float
A decimal number input. Accepts digits and one decimal point. Useful for prices, weights, percentages, coordinates, and any measurement.
{
id: 6,
title: 'Price (₹)',
variableName: 'price',
type: 'float',
placeholder: '999.99',
validations: {
isRequired: true,
minValue: 0,
maxValue: 1000000,
minValueError: 'Price cannot be negative.',
maxValueError: 'Price cannot exceed ₹10,00,000.',
},
}dropdown
A styled single-select dropdown built with Radix UI (fully keyboard-accessible, ARIA-compliant). Best for 3–15 options that fit in a list.
{
id: 7,
title: 'Country',
variableName: 'country',
type: 'dropdown',
placeholder: 'Select a country…',
options: [
{ value: 'in', label: 'India' },
{ value: 'us', label: 'United States' },
{ value: 'gb', label: 'United Kingdom' },
{ value: 'au', label: 'Australia' },
{ value: 'ca', label: 'Canada' },
],
validations: { isRequired: true },
}SelectOption shape:
{
value: string | number; // what gets submitted
label?: string; // what the user sees
title?: string; // fallback if no label
isDisabled?: boolean; // greys out and blocks selection
}Submitted value: the selected value, e.g. 'in'.
reactSelect (searchable single-select)
A searchable dropdown — the user types to filter the list in real time. Ideal for long option lists (states, cities, product codes, 50+ items). Shows a search box inside the dropdown.
{
id: 8,
title: 'Tech Stack',
variableName: 'techStack',
type: 'reactSelect',
placeholder: 'Search or pick one…',
options: [
{ value: 'react', label: 'React' },
{ value: 'vue', label: 'Vue' },
{ value: 'angular', label: 'Angular' },
{ value: 'svelte', label: 'Svelte' },
{ value: 'solid', label: 'SolidJS' },
{ value: 'next', label: 'Next.js' },
],
validations: { isRequired: true },
}When to use reactSelect vs dropdown:
dropdown→ 3–15 options, simple listreactSelect→ 15+ options, user needs to search
multiSelect
A searchable multi-select field. The user types to filter, then clicks to select. Each selected item appears as a removable chip inside the input. Useful for skills, categories, tags, and permissions.
{
id: 9,
title: 'Skills',
variableName: 'skills',
type: 'multiSelect',
placeholder: 'Add skills…',
options: [
{ value: 'ts', label: 'TypeScript' },
{ value: 'node', label: 'Node.js' },
{ value: 'gql', label: 'GraphQL' },
{ value: 'docker', label: 'Docker' },
{ value: 'k8s', label: 'Kubernetes' },
{ value: 'aws', label: 'AWS' },
],
}Submitted value: an array of selected values — ['ts', 'node', 'docker']
radioButton
A horizontal row of radio buttons. Best for 2–5 mutually exclusive choices where the user needs to see all options at once without opening a dropdown.
{
id: 10,
title: 'Preferred Contact Method',
variableName: 'contactMethod',
type: 'radioButton',
options: [
{ value: 'email', label: 'Email' },
{ value: 'phone', label: 'Phone' },
{ value: 'whatsapp', label: 'WhatsApp' },
],
radioColor: '#6366f1',
validations: {
isRequired: true,
isRequiredError: 'Please select a contact method.',
},
}radioColor — override the accent colour of the selected radio dot. Useful when you need a specific brand colour without changing the whole form theme.
Submitted value: the value of the selected option, e.g. 'email'.
switch / boolean
A toggle switch (on/off). The label sits next to the switch. Ideal for preferences, feature flags, account status.
{
id: 11,
title: 'Receive email notifications',
variableName: 'emailNotifications',
type: 'switch',
isChecked: true, // default state
}
type: 'boolean'is an alias fortype: 'switch'— they are identical.
isChecked — set true to start the switch in the ON state. Default is false.
Submitted value: true or false.
checkbox
A single checkbox. Most commonly used for terms & conditions acceptance, GDPR consent, or any opt-in.
{
id: 12,
title: 'I agree to the Terms & Conditions',
variableName: 'termsAccepted',
type: 'checkbox',
validations: {
isRequired: true,
isRequiredError: 'You must accept the Terms & Conditions to continue.',
},
}Submitted value: true (checked) or false (unchecked).
chipDisplay
A read-only display of chip/tag labels. Use this to show pre-assigned roles, labels, or categories that the user cannot change (e.g. "your assigned permissions are: Editor, Reviewer").
{
id: 13,
title: 'Assigned Roles',
variableName: 'roles',
type: 'chipDisplay',
options: [
{ value: 'editor', label: 'Editor' },
{ value: 'reviewer', label: 'Reviewer' },
{ value: 'viewer', label: 'Viewer' },
],
}The chips are display-only — the user cannot click, remove, or add them.
dateField
A calendar popover for picking a single date. Clicking the field opens a month/year calendar. The user navigates months with arrows and clicks a day. The selected date appears as formatted text in the field.
{
id: 14,
title: 'Date of Birth',
variableName: 'dob',
type: 'dateField',
validations: {
isRequired: true,
maxYearMinus: 0, // cannot be today or in the future
minYearMinus: 100, // cannot be more than 100 years in the past
},
}Submitted value: a date string in DD/MM/YYYY format, e.g. '25/12/1990'.
See the Date validation rules section for the full list of date constraint keys.
dateRange
A dual-calendar date range picker. The user picks a start date and an end date. Both calendars open in a popover side by side.
{
id: 15,
title: 'Project Timeline',
variableName: 'timeline',
type: 'dateRange',
validations: {
isRequired: true,
minDaysPlus: 0, // start date can be today
maxDaysPlus: 365, // end date can be up to 1 year from today
},
}Submitted value:
{ from: '15/06/2025', to: '30/09/2025' }uploadFile
A drag-and-drop file upload zone. Shows a dashed border with an upload icon. After the user selects a file, a preview appears (image thumbnail for images, filename for other types). Supports multi-file uploads.
{
id: 16,
title: 'Supporting Documents',
variableName: 'documents',
type: 'uploadFile',
acceptedExtensions: {
'application/pdf': ['.pdf'],
'image/*': ['.png', '.jpg', '.jpeg'],
},
validations: {
isRequired: true,
maxFileSize: 5 * 1024 * 1024, // 5 MB per file
maxFiles: 3, // allow up to 3 files
minFiles: 1,
},
errorOnFileTooLarge: 'Each file must be under 5 MB.',
errorForInvalidFileType: 'Only PDF, PNG, and JPG files are accepted.',
}Key props for uploadFile:
| Prop | Type | Description |
|---|---|---|
| acceptedExtensions | Record<string, string[]> | MIME type → extensions map. Follows dropzone/MIME format |
| validations.maxFileSize | number | Maximum size in bytes (e.g. 2 * 1024 * 1024 = 2 MB) |
| validations.maxFiles | number | Maximum number of files the user can select |
| validations.minFiles | number | Minimum number of files required |
| validations.exactFiles | number | Require exactly this many files |
| errorOnFileTooLarge | string | Message shown when a file exceeds maxFileSize |
| errorForInvalidFileType | string | Message shown when the file extension is not in acceptedExtensions |
Single image upload — max 5 MB:
{
id: 17,
title: 'Profile Photo',
variableName: 'photo',
type: 'uploadFile',
acceptedExtensions: { 'image/*': ['.png', '.jpg', '.jpeg', '.webp'] },
validations: { maxFileSize: 5 * 1024 * 1024, maxFiles: 1 },
errorOnFileTooLarge: 'Photo must be under 5 MB.',
errorForInvalidFileType: 'Only image files allowed (PNG, JPG, WebP).',
}Searching on the server and long lists (reactSelect, multiSelect)
Lists over 100 options render only the visible rows, so a list of ~1,500 RTO codes opens instantly (virtualizeThreshold changes the cut-off).
For server-side search, give reactSelect a loadOptions function instead of options:
{
id: 'rto', title: 'RTO', variableName: 'rto', type: 'reactSelect',
loadOptions: (query) => api.searchRto(query), // → Promise<SelectOption[]>
minSearchLength: 2, // default 1; 0 loads on open
searchDebounceMs: 300, // default
valueAs: 'option', // optional: store { value, label }
}Typing is debounced, a stale reply never overwrites a newer one, and the chosen option's label stays visible after the results change.
multiSelect and checkboxGroup accept validations.minSelected / maxSelected (with minSelectedError / maxSelectedError); options beyond the maximum are disabled.
checkboxGroup
Several checkboxes; stores an array of option values (shape per valueAs).
{ id: 'docs', title: 'Documents received', variableName: 'docs', type: 'checkboxGroup',
options: [{ value: 'rc', label: 'RC' }, { value: 'invoice', label: 'Invoice' }, { value: 'kyc', label: 'KYC' }],
validations: { minSelected: 2 } }otp
A one-time code in separate digit boxes. Typing advances, Backspace goes back, pasting fills every box. Stores a string and validates with the otp validator.
{ id: 'otp', title: 'Verification code', variableName: 'otp', type: 'otp',
validations: { isRequired: true, length: 6 } } // length defaults to 6monthYear
A month-and-year picker (e.g. manufacture month). Stores 'YYYY-MM' (valueAs: 'date' stores a Date on the 1st); reads 'YYYY-MM', 'MM/YYYY' or a Date. Takes the same bounds as dateField, compared by month; months outside them are disabled and validated.
{ id: 'mfg', title: 'Manufacture month', variableName: 'mfg', type: 'monthYear',
validations: { isRequired: true, maxDate: 'today', minYearMinus: 15 } }repeater
A list of rows, each with its own sub-fields; stores an array of objects. Sub-field names are relative to the row.
{
id: 'steps', title: 'Step', variableName: 'steps', type: 'repeater',
addLabel: 'Add step',
itemLabel: (i) => `Step ${i + 1}`,
validations: { minSelected: 1, maxSelected: 20 }, // row count
fields: [
{ id: 'action', title: 'Action', variableName: 'action', type: 'textField', containerClass: 'col-12 col-md-8', validations: { isRequired: true } },
{ id: 'expected', title: 'Expected result', variableName: 'expected', type: 'textField', containerClass: 'col-12 col-md-4' },
],
}
// submits { steps: [{ action: 'Open login', expected: 'Login page shows' }, …] }heading / divider
Layout-only entries in the grid (no value): { id: 'h', title: 'Nominee', variableName: '_h', type: 'heading', note: 'Optional sub-text' } and { id: 'd', title: '', variableName: '_d', type: 'divider' }.
6. Smart field-type constraints
Setting validations.fieldType on a textField applies, as the user types:
- Character filter — characters the type can never contain are blocked
- Hard
maxLengthcap - Auto-uppercase — for code fields like PAN, GST, chassis
- Mobile keyboard hint and a sensible
autocompleteattribute
…and on change, quantique-field-validator checks the format and shows its specific message. The filter never blocks a value the validator accepts (this is covered by a test for every type).
Names keep what was typed.
name,firstName,middleName,lastName,companyNameanddisplayNamedo not filter characters or trim spaces — a leading/trailing space, a double space, a digit or a symbol is shown as an error ("Remove the space at the start or end of the name") instead of being silently changed.
All built-in fieldType values
| fieldType | Character filter | Max length | Auto-UPPER | Keyboard |
|---|---|---|---|---|
| mobile | Digits | 10 | No | Numeric |
| aadhaar | Digits | 12 | No | Numeric |
| pincode | Digits | 6 | No | Numeric |
| number | Digits | — | No | Numeric |
| float | Digits + . | — | No | Decimal |
| otp | Digits | — | No | Numeric |
| age | Digits | 3 | No | Numeric |
| bankAccount | Digits | 18 | No | Numeric |
| micr | Digits | 9 | No | Numeric |
| ckycNumber | Digits | 14 | No | Numeric |
| gstStateCode | Digits | 2 | No | Numeric |
| pan | Alphanumeric | 10 | Yes | Text |
| gst | Alphanumeric | 15 | Yes | Text |
| ifsc | Alphanumeric | 11 | Yes | Text |
| rto | Alphanumeric + - | 8 | Yes | Text |
| chassis | Alphanumeric | 22 | Yes | Text |
| engine | Alphanumeric | 20 | Yes | Text |
| voterId | Alphanumeric | 10 | Yes | Text |
| drivingLicence | Alphanumeric | 15 | Yes | Text |
| passport | Alphanumeric | 8 | Yes | Text |
| cin | Alphanumeric | 21 | Yes | Text |
| ckycReference | Alphanumeric | 20 | No | Text |
| transactionRef | Alphanumeric | 30 | No | Text |
| alphanumeric | Alphanumeric | — | No | Text |
| code | Alphanumeric + _ - | — | Yes | Text |
| registrationNumber | Alphanumeric + space + - | 20 | Yes | Text |
| regCode | Letters | 3 | Yes | Text |
| regNumber | Digits | 4 | No | Numeric |
| policyNumber | Alphanumeric + / - | 30 | No | Text |
| phone | Digits + space - / , ( ) + . | — | No | Tel |
| username | Alphanumeric + . _ @ - | 64 | No | Text |
| hexColor | # + hex digits | 9 | No | Text |
| ip | Hex digits + . : | — | No | Text |
| name, firstName, middleName, lastName, companyName, displayName | (none — validator reports) | — | No | Text |
| email, url | (none) | — | No | Email / URL |
| string, address, freeText, password, custom | (none) | — | No | Text |
What each type accepts is defined by quantique-field-validator — see its README.
Examples
// PAN — the 4th character must be a holder type; individuals may not hold a 'C' PAN
{ id: 1, title: 'PAN', variableName: 'pan', type: 'textField',
validations: { fieldType: 'pan', holderType: 'individual', isRequired: true } }
// Last name — "Brij Sinha" is valid; " Brij" or "Brij Sinha" shows an error
{ id: 2, title: 'Last name', variableName: 'lastName', type: 'textField',
validations: { fieldType: 'lastName', isRequired: true, maxLength: 50 } }
// Chassis — 17–22 characters, no I/O/Q, ending in 4 digits
{ id: 3, title: 'Chassis No.', variableName: 'chassis', type: 'textField',
validations: { fieldType: 'chassis', isRequired: true } }
// Your own pattern — a regex alone is enough (fieldType defaults to 'custom')
{ id: 4, title: 'Branch code', variableName: 'branch', type: 'textField',
validations: { regex: '^[A-Z]{3}[0-9]{3}$', regexError: 'Three letters and three digits, e.g. PUN001' } }7. Override auto-constraints
Auto-constraints are applied by default when you set fieldType. You can override any individual constraint in the validations object without turning off the others.
Available overrides
| Override | Type | Effect |
|---|---|---|
| maxLength: N | number | Change the character cap. 0 = remove the cap entirely |
| allowLowerCase: true | boolean | Allow lowercase input on fields that auto-uppercase (e.g. PAN, GST) |
| isUpperCase: true | boolean | Force uppercase on any field, even those without auto-upper |
| allowAnyChars: true | boolean | Disable the character filter entirely — any character can be typed |
| isNumeric: true | boolean | Force digit-only filter on fields that have no built-in filter |
Examples
// Mobile field with a shorter cap (8 digits instead of 10)
{
validations: {
fieldType: 'mobile',
maxLength: 8, // overrides the default max of 10
},
}
// PAN field — allow lowercase (e.g. for a case-insensitive lookup form)
{
validations: {
fieldType: 'pan',
allowLowerCase: true, // user can type 'abcde1234f', it won't be uppercased
},
}
// GST field — allow any characters (e.g. import/search form that accepts partial input)
{
validations: {
fieldType: 'gst',
allowAnyChars: true, // character filter removed, user can type anything
},
}
// Mobile field with no length cap (for international numbers)
{
validations: {
fieldType: 'mobile',
maxLength: 0, // 0 = no cap; the digits-only filter still applies
},
}
// Plain string field — force uppercase
{
validations: {
fieldType: 'string',
isUpperCase: true,
},
}8. Full ValidationConfig reference
ValidationConfig extends quantique-field-validator's ValidationRules, so every validator option can be set here and is forwarded — holderType, checksum, allowPrefix, allowMasked, multiple, pan, case, series, label, customValidator, password policy options, and so on.
interface ValidationConfig {
// Required
isRequired?: boolean;
isRequiredError?: string; // alias: errorMessages.required
// Which validator runs
fieldType?: ValidatorType; // default: 'custom' when only `regex` is set, 'email' for type 'email'
regex?: string | RegExp; // replaces the type's pattern; '/pattern/flags' strings accepted
regexError?: string; // alias: errorMessages.regex
// Length
minLength?: number;
maxLength?: number; // hard cap while typing; 0 = no cap
minLengthError?: string; // alias: errorMessages.minLength
maxLengthError?: string; // alias: errorMessages.maxLength
// Numbers
minValue?: number;
maxValue?: number;
minValueError?: string;
maxValueError?: string;
// Keystroke-filter overrides
isNumeric?: boolean;
isUpperCase?: boolean;
allowLowerCase?: boolean;
allowAnyChars?: boolean;
// Dates (section 9)
minDate?: string | Date; // ISO 'YYYY-MM-DD', a Date, or 'today'
maxDate?: string | Date;
minDateError?: string;
maxDateError?: string;
minYearMinus?: number; maxYearMinus?: number;
minYearPlus?: number; maxYearPlus?: number;
minDaysPlus?: number; maxDaysPlus?: number;
minDaysMinus?: number; maxDaysMinus?: number;
// Files
multiple?: boolean;
maxFileSize?: number | string; // bytes, or '5MB' / '500KB'
minFiles?: number;
maxFiles?: number;
exactFiles?: number;
// Messages — any validator message key
errorMessages?: { required?: string; invalid?: string; regex?: string; [key: string]: string | undefined };
// …plus every other quantique-field-validator option
}Which message is shown: the validator's specific message (e.g. "The first two digits of a GSTIN are its state code"). errorMessages.invalid / regexError replace the generic format message; they no longer hide every other message.
9. Date validation rules
Date bounds work on dateField and dateRange. Every key you set applies at once — the tightest bound wins — and bounds are compared by calendar day, so minDaysPlus: 0 allows today.
Bounds are real validation rules: the calendar greys out days outside them, and a seeded, restored or setValue'd date outside them shows an error.
| Key | Meaning | Example |
|---|---|---|
| minDate / maxDate | Absolute bound: ISO 'YYYY-MM-DD', a Date, or 'today' | maxDate: 'today' → not in the future |
| minDaysPlus / maxDaysPlus | At least / at most N days after today | { minDaysPlus: 0, maxDaysPlus: 90 } |
| minDaysMinus / maxDaysMinus | No earlier than / at least N days before today | { maxDaysMinus: 0 } |
| minYearMinus / maxYearMinus | No earlier than / at least N years before today | DOB: { minYearMinus: 100, maxYearMinus: 18 } |
| minYearPlus / maxYearPlus | At least / at most N years after today | { minYearPlus: 1, maxYearPlus: 10 } |
| minDateError / maxDateError | Messages for the two bounds | |
Values: a dateField reads a Date, an ISO string or a timestamp. A value it cannot read is shown empty (with a console warning in development) instead of crashing the page. It stores a local Date; set valueAs: 'isoDate' to store 'YYYY-MM-DD' or valueAs: 'isoDateTime' for 'YYYY-MM-DDTHH:mm'. With showTime, the time starts from the existing value.
10. Sections — grouping fields visually
Instead of a flat fields array, use sections to visually group related fields under labelled headings with a separator line.
import { DynamicForm } from 'quantique-forms';
import type { FormSection } from 'quantique-forms';
const sections: FormSection[] = [
{
id: 'personal',
title: 'Personal Information',
fields: [
{ id: 1, title: 'Full Name', variableName: 'fullName', type: 'textField', validations: { isRequired: true } },
{ id: 2, title: 'Mobile', variableName: 'mobile', type: 'textField', validations: { fieldType: 'mobile' } },
{ id: 3, title: 'Date of Birth', variableName: 'dob', type: 'dateField', validations: { maxYearMinus: 18 } },
],
},
{
id: 'identity',
title: 'Identity Documents',
fields: [
{ id: 4, title: 'PAN Card', variableName: 'pan', type: 'textField', validations: { fieldType: 'pan' } },
{ id: 5, title: 'Aadhaar', variableName: 'aadhaar', type: 'textField', validations: { fieldType: 'aadhaar' } },
],
},
{
id: 'vehicle',
title: 'Vehicle Details',
fields: [
{ id: 6, title: 'Chassis No.', variableName: 'chassis', type: 'textField', validations: { fieldType: 'chassis' } },
{ id: 7, title: 'Engine No.', variableName: 'engine', type: 'textField', validations: { fieldType: 'engine' } },
],
},
];
export default function MultiSectionForm() {
return (
<DynamicForm
sections={sections}
onSubmit={(data) => console.log(data)}
renderActions={(isSubmitting) => (
<button type="submit" disabled={isSubmitting}>Submit</button>
)}
/>
);
}What the user sees: Each section renders with its title as a heading and a visual separator between sections. All fields still validate together on submit.
Use either
fieldsORsections— not both. If you passsections, the top-levelfieldsprop is ignored.
11. Theming and styling
The stylesheet is safe in any app
import 'quantique-forms/styles' only styles the form:
- Scoped. Every rule only matches inside
.qf-root(the<form>and each field cell) or.qf-portal(popovers rendered in a portal). Nothing on your page changes. - No global reset. Tailwind's preflight is not shipped; a zero-specificity reset applies inside the form only.
- No cascade layers. Your plain element rules (
p { margin: 0 }, Bootstraplabel { … }) no longer beat the form's own classes; normal specificity decides, and any class you add wins over the reset. - No variables on
:root. Every token is read with a fallback, so set--qf-*on any ancestor — or:root— to theme.
Theme with CSS variables or the theme prop
/* every form on the page */
:root { --qf-brand: #6366f1; --qf-radius: 0.375rem; }
/* or one area */
.tenant-acme { --qf-brand: #0f766e; --qf-on-brand: #ffffff; }<DynamicForm theme={{ brand: '#6366f1', radius: '0.375rem', popoverZ: '1100' }} … />The theme prop is applied to the form and to its popovers and dropdown lists (which render outside the form).
Brand shades derive from the brand. Set only --qf-brand; hover, light and muted shades are mixed from it unless you set them too. --qf-on-brand is the text colour on brand fills — set it to a dark colour for light brands (e.g. yellow).
| Variable | theme key | Default | Used for |
|---|---|---|---|
| --qf-brand | brand | #fe7c0b | Selected states, focus, buttons in pickers |
| --qf-brand-hover / -light / -muted | brandHover / brandLight / brandMuted | mixed from brand | Hover, tints |
| --qf-on-brand | onBrand | #ffffff | Text/icons on brand fills |
| --qf-ink / -muted / -light / -subtle / -dark | ink … | slate scale | Text |
| --qf-surface / -muted | surface / surfaceMuted | #f8fafc / #f1f5f9 | Panels, dropzone |
| --qf-surface-raised | surfaceRaised | #ffffff | Popovers, dropdown lists, cards |
| --qf-border / -muted | borderDefault / borderMuted | #e2e8f0 / #cbd5e1 | Borders |
| --qf-danger (+ -light, -faint, -dark) | danger … | red | Errors |
| --qf-success, --qf-warning (+ shades) | success, warning … | green / amber | Status |
| --qf-note | note | ink-muted | Helper notes under fields |
| --qf-radius | radius | 0.5rem | Input corners |
| --qf-font-sans | fontSans | inherit | Font |
| --qf-focus-ring | focusRing | 18% brand | Focus ring |
| --qf-popover-z | popoverZ | 50 | z-index of popovers / dropdown lists |
| --qf-color-scheme | colorScheme | light | Native controls (dark for dark themes) |
| --qf-section-gap | — | 2rem | Space between sections |
Input surface (all optional): --qf-field-bg, --qf-field-bg-focus, --qf-field-bg-disabled, --qf-field-border, --qf-field-border-hover, --qf-field-border-disabled, --qf-field-border-disabled-style, --qf-field-shadow, --qf-field-shadow-hover, --qf-field-shadow-focus, --qf-field-shadow-disabled, --qf-field-ink-disabled.
Flat look: <DynamicForm variant="flat" /> drops the gradient and depth.
Popovers inside modals
Dropdown lists and date pickers render in a portal. Inside a modal:
<DynamicForm portalContainer={modalRootElement} … /> // render inside the modal
// or
<DynamicForm theme={{ popoverZ: '1100' }} … /> // or raise them above itLayout
containerClassuses Bootstrap-style columns ('col-12 col-md-6 col-lg-4') on a 12-column grid.responsive="container"measures those breakpoints against the form's own width — for forms in drawers, modals and side panels.gridClassName,actionsClassName,unstyledActionsand--qf-section-gapadjust the grid, the actions bar and section spacing.- Grid cells align to the top and have
min-width: 0, so long content cannot widen the page.
Styling hooks
Stable class names and attributes you can target from your own CSS (they are part of the public API):
| Hook | Element |
|---|---|
| .qf-form | the <form> (with data-qf-variant) |
| .qf-section, .qf-section__header, .qf-section__title, .qf-section__description | a section |
| .qf-grid | a section's 12-column grid |
| .qf-field, .qf-field--{type}, [data-field-name], [data-field-type], [data-invalid], [data-disabled] | a field's grid cell |
| .qf-label, .qf-label__required | the label and its asterisk |
| .qf-control | text inputs, textareas, select/date/combobox triggers |
| .qf-error, .qf-note | error message, helper note |
| .qf-dropzone | the upload drop area |
| .qf-popover, .qf-option | a popover / dropdown list and its options |
| .qf-actions | the actions bar |
/* example: full-width buttons */
.my-form .qf-actions { justify-content: stretch; border-top: 0; }12. Inter-field reactivity
The onFieldChange callback fires every time any field value changes. Use it to show/hide fields, pre-fill values, trigger API calls, or sync one field's value to another.
<DynamicForm
fields={fields}
onSubmit={handleSubmit}
renderActions={...}
onFieldChange={(name, value, allValues, setValue) => {
// name — the variableName of the field that changed
// value — the new value of that field
// allValues — a snapshot of every field's current value
// setValue — react-hook-form's setValue — use this to programmatically set any field
if (name === 'country' && value === 'in') {
// Auto-fill currency when country is India
setValue('currency', 'INR');
}
if (name === 'vehicleType' && value === 'electric') {
// Clear engine number for electric vehicles
setValue('engineNo', '');
}
}}
/>Practical examples
Auto-fill city from pincode:
onFieldChange={async (name, value, _all, setValue) => {
if (name === 'pincode' && String(value).length === 6) {
const city = await fetchCityFromPincode(String(value));
if (city) setValue('city', city);
}
}}Cascade dropdown — state → city:
onFieldChange={(name, value, _all, setValue) => {
if (name === 'state') {
// Reset city when state changes
setValue('city', '');
// You can also update the city field's options via your state management
}
}}Log all changes for debugging:
onFieldChange={(name, value) => {
console.log(`${name} →`, value);
}}13. Pre-filling default values
Pass defaultValues (keys = variableName), or set value on a field config — explicit defaultValues win.
<DynamicForm
fields={fields}
onSubmit={handleSubmit}
defaultValues={{ fullName: record.name, email: record.email, dob: record.dob }}
/>- Compared by content. Passing a new object with the same values (e.g. an inline literal on every render) does not reset the form or wipe what the user typed. When the values change, the form re-seeds.
resetKey— change it to force a re-seed (e.g. after reloading the same record).- No errors on open. Seeding no longer validates every field, so a prefilled form does not open full of "… is required". Pass
validateOnMountto validate immediately.
14. Custom submit / action buttons
The renderActions prop gives you full control over the submit/reset/cancel buttons. The function receives isSubmitting (boolean) so you can show a loading state.
Submit + Reset:
renderActions={(isSubmitting) => (
<div style={{ display: 'flex', gap: 12 }}>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Saving…' : 'Save changes'}
</button>
<button type="reset">
Reset
</button>
</div>
)}Save draft + Publish:
renderActions={(isSubmitting) => (
<div style={{ display: 'flex', gap: 12 }}>
<button type="submit" disabled={isSubmitting}>
Publish
</button>
<button type="button" onClick={handleSaveDraft}>
Save draft
</button>
<button type="button" onClick={handleCancel}>
Cancel
</button>
</div>
)}
type="reset"clears the form.type="submit"triggers validation andonSubmit.type="button"does neither — useful for secondary actions like "save draft" or "go back".
15. DynamicForm prop reference
| Prop | Type | Description |
|---|---|---|
| fields / sections | FieldConfig[] / FormSection[] | The fields, flat or grouped (one of the two is required) |
| onSubmit | (data, methods) => void \| Promise<void> | Required. Called when every field is valid; methods are the react-hook-form methods (reset, setError…) |
| onInvalid | (errors) => void | Called when submit is blocked by validation errors |
| scrollToFirstError | boolean | Scroll to and focus the first invalid field on a blocked submit (default true) |
| formId | string | id on the <form> — a button elsewhere submits it with form={formId} |
| form | UseFormReturn | Your own useForm() instance (watch, setValue, reset… from outside) |
| mode / reValidateMode | react-hook-form modes | When validation runs (default 'onChange'); ignored when form is passed |
| ref | DynamicFormHandle | submit(), reset(), setValue, getValues, trigger, setError, clearErrors, setFocus, methods |
| defaultValues | Record<string, unknown> | Initial values (compared by content) |
| resetKey | unknown | Change to force a re-seed |
| validateOnMount | boolean | Validate as soon as values are seeded (default false) |
| errors | Record<string, string> | Server errors by variableName; each stays until the user edits that field |
| onFieldChange | (name, value, allValues, setValue) => void | Called on every field change |
| onValuesChange | (values) => void | Called with all values on every change |
| renderActions | (isSubmitting, state) => ReactNode | Your buttons; state has isValid, isDirty, submitCount, errors, reset |
| unstyledActions | boolean | Render the actions without the right-aligned bar and top border |
| disabled / readOnly | boolean | Disable every field / make every field read-only (values still submitted) |
| loading | boolean | Show placeholders instead of fields |
| customFields | Record<string, Component> | Components for custom type names |
| renderSection | (section, children, progress) => ReactNode | Wrap each section; progress = { required, answered, missing } |
| theme | FormTheme | Theme tokens; applied to the form and its popovers |
| variant | '3d' \| 'flat' | Field look (default '3d') |
| portalContainer | HTMLElement \| null | Where popovers render (default document.body) |
| responsive | 'viewport' \| 'container' | Breakpoints from the viewport (default) or the form's own width |
| gridClassName / actionsClassName | string | Extra classes on the field grid / actions bar |
| className | string | Class on the <form> |
16. FieldConfig full reference
| Key | Type | Required | Description |
|---|---|---|---|
| id | number \| string | Yes | Unique identifier within the form |
| title | string | Yes | Label shown above the field |
| variableName | string | Yes | Key in the submitted data object |
| type | FieldType | Yes | Which field component to render (see section 5) |
| placeholder | string | No | Placeholder text inside the input |
| info | string | No | Helper text shown below the label |
| note | string | No | Additional note shown below the field |
| options | SelectOption[] | For choice types | Options for dropdown, radioButton, multiSelect, etc. |
| validations | ValidationConfig | No | All validation rules and constraints |
| isDisabled | boolean | No | Disable the field (greyed out, not editable) |
| isChecked | boolean | No | Default ON state for switch / boolean |
| showTime | boolean | No | Show time picker alongside calendar in dateField |
| rowSize | number | No | Number of text rows for multiTextField |
| radioColor | string | No | Custom colour for radioButton selected dot |
| acceptedExtensions | Record<string, string[]> | No | MIME type → extension map for uploadFile |
| errorOnFileTooLarge | string | No | Error message for oversized files in uploadFile |
| errorForInvalidFileType | string | No | Error message for wrong file type in uploadFile |
| containerClass | string | No | Grid placement, Bootstrap-style: 'col-12 col-md-6 col-lg-4'. An explicit value always wins ('col-12' = full width). Default: full / half / third; textareas, uploads and date ranges full width |
| value | unknown | No | Initial value; merged into the form's defaults (defaultValues win). Also seeds checkbox / switch |
| valueAs | 'string' \| 'value' \| 'option' \| 'date' \| 'isoDate' \| 'isoDateTime' | No | Stored shape. Choices: 'string' (default) / 'value' (original type, e.g. number or boolean) / 'option' (whole option). Dates: 'date' (default) / 'isoDate' / 'isoDateTime' |
| validate | (value, allValues) => true \| string | No | Cross-field rule, e.g. confirm password |
| deps | string[] | No | Re-validate when these fields change |
| autoComplete | string | No | Overrides the input's autocomplete (e.g. 'new-password') |
| hidden | boolean | No | Hide the field (not validated; not submitted unless keepValueWhenHidden) |
| visibleWhen | (values) => boolean | No | Show only when this returns true |
| disabledWhen | (values) => boolean | No | Disable when this returns true |
| keepValueWhenHidden | boolean | No | Keep the value in submitted data while hidden |
| isReadOnly | boolean | No | Not editable; value still submitted |
| onChange | (value, { setValue, getValues, values }) => void | No | Runs when this field changes — e.g. fill the PAN from a GSTIN |
| render | Component<{ field }> | No | Render this one field with your own component |
| renderAfter | ReactNode | No | Extra content after the field, inside its grid cell |
| note | ReactNode | No | Helper text (may be markup, e.g. a password-rules list) |
| loadOptions | (query) => Promise<SelectOption[]> | No | Server search for reactSelect |
| minSearchLength / searchDebounceMs | number | No | When loadOptions runs (defaults 1 / 300 ms) |
| virtualizeThreshold | number | No | Lists longer than this render only visible rows (default 100) |
| fields | FieldConfig[] | For repeater | Sub-fields of each row |
| addLabel / itemLabel | string / (i) => string | No | Repeater add-button label / row title |
17. TypeScript types
Typed values
DynamicForm is generic over your values type; it types onSubmit, form, defaultValues, onValuesChange, onFieldChange, renderActions state and the ref:
type Owner = { firstName: string; lastName: string; dob: Date | null };
const formRef = useRef<DynamicFormHandle<Owner>>(null);
<DynamicForm<Owner>
ref={formRef}
fields={OWNER_FIELDS}
defaultValues={{ firstName: '' }}
onSubmit={(owner, methods) => save(owner)} // owner: Owner
/>Without a type argument, values are Record<string, unknown> (as before).
Field lists without casts
An array built without an annotation widens type: 'textField' to string, which then needs as FieldConfig. Use the helpers instead — every entry is checked against FieldConfig:
import { defineFields, defineSections, field } from 'quantique-forms';
export const OWNER_FIELDS = defineFields([
{ id: 'first', title: 'First name', variableName: 'firstName', type: 'textField',
validations: { fieldType: 'firstName', isRequired: true } },
]);
const docFields = docs.map((d) => field({ id: d.code, title: d.label, variableName: d.code, type: 'uploadFile' }));type also accepts custom type names (for customFields), so a misspelt built-in type is not a compile error; in development a console warning names it, and keys the engine never reads (typos, or validation keys placed beside validations) are warned about the same way.
Exported types
import type {
FieldConfig, FieldType, FormSection, SelectOption, ValidationConfig,
DynamicFormProps, DynamicFormHandle, ActionsState, FormTheme, FormValues,
CustomFieldProps, FieldChangeHelpers, RequiredProgress,
} from 'quantique-forms';ValidationConfig extends quantique-field-validator's ValidationRules, and fieldType is typed as its ValidatorType.
Package
- Dependencies are not bundled — your bundler resolves and de-duplicates them (
dist/index.mjs≈ 180 kB, was ≈ 2.2 MB; ExcelJS loads on demand from yournode_moduleswhen a spreadsheet is previewed). "sideEffects": ["*.css"]— unused exports are tree-shaken.- The JS never imports CSS; load
quantique-forms/stylesonce. - CJS and ESM builds both load in plain Node.
18. Real-world example — vehicle registration form
A complete vehicle insurance registration form using sections, smart field-type constraints, date rules, and file upload:
import 'quantique-forms/styles';
import { DynamicForm } from 'quantique-forms';
import type { FormSection } from 'quantique-forms';
const sections: FormSection[] = [
{
id: 'owner',
title: 'Owner Details',
fields: [
{
id: 1,
title: 'Full Name',
variableName: 'ownerName',
type: 'textField',
placeholder: 'Rajesh Kumar',
validations: { isRequired: true, fieldType: 'name' },
},
{
id: 2,
title: 'Mobile Number',
variableName: 'mobile',
type: 'textField',
placeholder: '9876543210',
validations: {
isRequired: true,
fieldType: 'mobile',
errorMessages: { invalid: 'Enter a valid 10-digit Indian mobile number.' },
},
},
{
id: 3,
title: 'PAN Card',
variableName: 'pan',
type: 'textField',
placeholder: 'ABCPE1234F',
validations: {
isRequired: true,
fieldType: 'pan',
holderType: 'individual',
},
},
{
id: 4,
title: 'Aadhaar Number',
variableName: 'aadhaar',
type: 'textField',
placeholder: '999941057058',
validations: {
isRequired: true,
fieldType: 'aadhaar',
errorMessages: { invalid: 'Enter a valid 12-digit Aadhaar number.' },
},
},
{
id: 5,
title: 'Date of Birth',
variableName: 'dob',
type: 'dateField',
validations: {
isRequired: true,
maxYearMinus: 18, // must be at least 18 years old
minYearMinus: 100,
},
},
],
},
{
id: 'vehicle',
title: 'Vehicle Details',
fields: [
{
id: 6,
title: 'Registration Code',
variableName: 'regCode',
type: 'textField',
placeholder: 'AB',
info: 'Letter series of the plate (the AB in MH12AB1234)',
validations: {
isRequired: true,
fieldType: 'regCode',
},
},
{
id: 7,
title: 'Registration Number',
variableName: 'regNumber',
type: 'textField',
placeholder: '1234',
info: 'Serial number of the plate (the 1234 in MH12AB1234)',
validations: {
isRequired: true,
fieldType: 'regNumber',
errorMessages: { invalid: 'Enter a valid registration number (1–4 digits).' },
},
},
{
id: 8,
title: 'Chassis Number',
variableName: 'chassis',
type: 'textField',
placeholder: 'MA3ERLF1S00100001',
validations: {
isRequired: true,
fieldType: 'chassis',
},
},
{
id: 9,
title: 'Engine Number',
variableName: 'engine',
type: 'textField',
placeholder: 'K12MN1234509',
validations: {
isRequired: true,
fieldType: 'engine',
},
},
{
id: 10,
title: 'Vehicle Purchase Date',
variableName: 'purchaseDate',
type: 'dateField',
validations: {
isRequired: true,
maxDaysMinus: 0, // must be in the past
},
},
],
},
{
id: 'insurance',
title: 'Insurance Details',
fields: [
{
id: 11,
title: 'Policy Number',
variableName: 'policyNumber',
type: 'textField',
placeholder: '3001/123456789/00/000',
validations: {
isRequired: true,
fieldType: 'policyNumber',
},
},
{
id: 12,
title: 'Policy Expiry Date',
variableName: 'policyExpiry',
type: 'dateField',
validations: {
isRequired: true,
minDaysPlus: 1, // must be a future date
},
},
{
id: 13,
title: 'Insurance Document',
variableName: 'insuranceDoc',
type: 'uploadFile',
acceptedExtensions: { 'application/pdf': ['.pdf'], 'image/*': ['.jpg', '.jpeg', '.png'] },
validations: {
isRequired: true,
maxFileSize: 5 * 1024 * 1024,
maxFiles: 1,
},
errorOnFileTooLarge: 'Document must be under 5 MB.',
errorForInvalidFileType: 'Only PDF, JPG, or PNG accepted.',
},
],
},
{
id: 'consent',
title: 'Consent',
fields: [
{
id: 14,
title: 'I confirm that all details are correct and I accept the Terms & Conditions.',
variableName: 'termsAccepted',
type: 'checkbox',
validations: {
isRequired: true,
isRequiredError: 'Please confirm and accept the terms to submit.',
},
},
],
},
];
export default function VehicleRegistrationForm() {
const handleSubmit = (data: Record<string, unknown>) => {
console.log('Form submitted:', data);
// data.ownerName, data.pan, data.chassis, data.policyNumber, etc.
};
return (
<DynamicForm
sections={sections}
onSubmit={handleSubmit}
theme={{
brand: '#1d4ed8',
brandHover: '#1e40af',
danger: '#dc2626',
radius: '0.5rem',
}}
renderActions={(isSubmitting) => (
<div style={{ display: 'flex', gap: 12 }}>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Registering…' : 'Register Vehicle'}
</button>
<button type="reset">Clear form</button>
</div>
)}
/>
);
}What this form validates automatically:
regCode— the 1–3 letter series (AB in MH12AB1234) — digits blocked at keystroke, auto-uppercasechassis— 17–22 uppercase letters/digits, no I/O/Q, ending in 4 digitsengine— 5–20 uppercase letters/digits with at least one letter and one digitpolicyNumber— 5–30 letters/digits as printed,/or-only between themdob— person must be at least 18 years oldpurchaseDate— must be in the pastpolicyExpiry— must be in the futurepan— ABCPE1234F format; the 4th letter is the holder type (an individual may not hold a 'C' PAN)aadhaar— 12 digits, first digit 2–9, valid Verhoeff check digitmobile— 10 digits, starts with 6–9
19. Advanced usage
Own the form: form, DynamicField without a provider
const form = useForm();
const vehicleType = form.watch('vehicleType');
<DynamicForm form={form} fields={fields} onSubmit={save} />
// or place single fields anywhere — no <FormProvider> needed
<DynamicField form={form} field={chassisField} />Submit from a modal footer: formId
<Modal footer={<Button type="submit" form="edit-user">Save</Button>}>
<DynamicForm formId="edit-user" fields={fields} onSubmit={save} />
</Modal>Imperative control: ref
const formRef = useRef<DynamicFormHandle>(null);
<DynamicForm ref={formRef} fields={fields} onSubmit={save} />
<Button onClick={() => formRef.current?.submit()}>Save</Button>
<Button onClick={() => formRef.current?.reset()}>Discard changes</Button>Server errors
const [serverErrors, setServerErrors] = useState({});
<DynamicForm
fields={fields}
errors={serverErrors} // { email: 'Already registered' }
onSubmit={async (data, methods) => {
const res = await api.save(data);
if (res.fieldErrors) setServerErrors(res.fieldErrors);
else methods.reset(data);
}}
/>Each message stays until the user edits that field.
Conditional and dependent fields
const fields: FieldConfig[] = [
{ id: 1, title: 'Holder', variableName: 'holder', type: 'radioButton',
options: [{ value: 'person', label: 'Person' }, { value: 'company', label: 'Company' }] },
{ id: 2, title: 'Company name', variableName: 'companyName', type: 'textField',
visibleWhen: (v) => v.holder === 'company',
validations: { fieldType: 'companyName', isRequired: true } },
{ id: 3, title: 'GSTIN', variableName: 'gst', type: 'textField',
validations: { fieldType: 'gst' },
onChange: (gst, { setValue }) => setValue('pan', String(gst).slice(2, 12)) },
{ id: 4, title: 'Confirm password', variableName: 'confirm', type: 'password',
deps: ['password'],
validate: (v, all) => v === all.password || 'Passwords do not match.' },
];A hidden field is not validated and is left out of the submitted data (keepValueWhenHidden keeps it).
Custom field types
import { useFieldController, FieldLabel, FieldError, type CustomFieldProps } from 'quantique-forms';
const MonthYearField = ({ field }: CustomFieldProps) => {
const { value, onChange, onBlur, error, labelProps, isDisabled } = useFieldController(field);
return (
<div>
<FieldLabel {...labelProps} />
<input id={field.variableName} value={(value as string) ?? ''} disabled={isDisabled}
onChange={(e) => onChange(e.target.value)} onBlur={onBlur} />
<FieldError message={error} />
</div>
);
};
<DynamicForm
customFields={{ monthYear: MonthYearField }}
fields={[{ id: 1, title: 'Manufactured', variableName: 'mfg', type: 'monthYear',
validations: { isRequired: true, fieldType: 'monthYear' } }]}
onSubmit={save}
/>useFieldController applies the same required, validator and cross-field rules as built-in fields. For a one-off, set render: MyComponent on the field instead of registering a type.
Headings, dividers and section cards
const fields = [
{ id: 'h1', title: 'Nominee', variableName: '_nominee', type: 'heading', note: 'Who receives the claim' },
// …nominee fields…
{ id: 'd1', title: '', variableName: '_d1', type: 'divider' },
];
<DynamicForm
sections={sections}
renderSection={(section, children, { answered, required }) => (
<Card title={section.title} badge={`${answered}/${required}`}>{children}</Card>
)}
onSubmit={save}
/>Sections also take description, className and hidden (boolean or (values) => boolean). useRequiredProgress(fields) returns the same { required, answered, missing } anywhere inside the form.
20. Accessibility
- Unique ids. Inside
DynamicForm, element ids are<prefix>-<variableName>; the prefix isidPrefix, elseformId, else generated — two forms with the same field names never share an id. ADynamicFieldused on its own keeps the barevariableName. - Errors and notes are announced. Each control's
aria-describedbypoints at its error and note;aria-invalidandaria-requiredare set on real controls. Picker buttons (date, month) expose the error througharia-describedbyanddata-invalid, becausearia-invalidis not allowed onrole="button". - Groups. Radio buttons are a labelled
role="radiogroup"; checkbox groups are a<fieldset>with a<legend>; OTP boxes are a labelled group with one label per digit. - Keyboard. In
reactSelectandmultiSelectsearch boxes, ArrowUp/ArrowDown move through options (skipping disabled ones), Home/End jump, Enter picks; the highlighted option is announced witharia-activedescendantand kept in view, also in virtualised lists. OTP boxes support arrows and Backspace. - Labels.
hideLabel: truehides the label visually but keeps it for screen readers. Theinfobutton is named "About …" and its tooltip is linked while shown (Escape closes it).
Prefer [data-field-name="…"] over ids when you need to find a field's element from your own code.
21. Changelog
v2.0.0
Requires quantique-field-validator 3.0 — its stricter, IMS-aligned defaults (PAN holder letter, GSTIN state code, Aadhaar checksum, chassis 17–22, multi-word last names…) now apply in every form.
Fixed
- Responsive grid had no CSS:
md:/lg:spans built fromcontainerClasswere never generated, so every form was one column. All spans are now in the stylesheet. containerClass: 'col-12'was turned into the compact third-width layout; explicit values now always win.defaultValuesreset the form — wiping user input — whenever a parent re-rendered with an inline object; it is now compared by content.- Seeding validated every field, so prefilled forms opened full of "required" errors (
validateOnMountrestores it). dateFieldcrashed the page ("Invalid time value") on a string it could not parse.- Date bounds: only the first key per side was used;
minDaysPlus: 0disabled today; bounds were not validated for seeded values;showTimereset the time to 00:00. theme.borderDefaultset a variable the stylesheet never read.- Dropdown/combobox lists could not scroll past the fold.
rtocould never pass (the filter removed the required-);chassisstopped at 17 characters;regCodeforced 2 letters;policyNumberstopped at 10 and blocked/and-.- A
regexwithoutfieldTypewas silently ignored;type: 'email'did not validate;validations.typewas overwritten with'user';errorMessages.invalidhid every specific validator message; textareas ignoredminLengthError/maxLengthError. - File upload: a renamed non-PDF/non-image passed and broke the preview; overlapping picks could overwrite each other; "required" showed before submit;
reset()did not clear the picked file; the MIME type was never checked.
Added
DynamicForm:resetKey,validateOnMount.FieldConfig:valueAs,validate,deps,autoComplete;valueseeds the form.validations: every quantique-field-validator option,regexError,minDateError/maxDateError,maxFileSize: '5MB',minDate/maxDateasDateor'today'.- New
fieldTypes from the validator (registration number, KYC documents, banking,code,username,otp, …) with matching keystroke filters. infotooltip on number, date, dropdown, radio and switch fields.- Form API:
form(own useForm instance),formId,ref(DynamicFormHandle),mode/reValidateMode,onSubmit(data, methods),onInvalid,scrollToFirstError,errors(server errors),onValuesChange,renderActions(isSubmitting, state),unstyledActions,disabled,readOnly,loading. - Conditional fields:
hidden,visibleWhen,disabledWhen,keepValueWhenHidden,isReadOnly, per-fieldonChange. - Custom fields:
customFieldsregistry,field.render,useFieldController;renderAfter;noteaccepts React nodes;headinganddividertypes. - Sections:
description,className,hidden,renderSection;useRequiredProgress,isEmptyValue. DynamicFieldacceptsformand works without a FormProvider.- Long lists:
reactSelect/multiSelectrender only visible rows above 100 options (virtualizeThreshold). - Server search:
loadOptions,minSearchLength,searchDebounceMsonreactSelect. - New field types:
checkboxGroup,otp,monthYear,repeater;minSelected/maxSelectedfor multiSelect, checkboxGroup and repeater rows. - Nested field n
