Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,24 @@ jobs:
- run: pnpm install --frozen-lockfile --ignore-scripts
- run: pnpm build
- run: pnpm test:browser

form-examples:
name: Eight form libraries / Chromium
runs-on: ubuntu-latest
timeout-minutes: 15
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001 --init --ipc=host
defaults:
run:
working-directory: examples/form-integrations
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444
with:
node-version: 24
package-manager-cache: false
- run: npm ci --ignore-scripts --no-audit --no-fund
- run: npm run test:contracts
- run: npm run build
- run: npm test
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,11 @@ Boundary tests cover all **912** supported prefix/payload length pairs and **1,7
## License

Original code: **MIT OR Apache-2.0**, at your option. Standard checksum/reference attribution and separately licensed test vectors are recorded in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).

### Form validation examples

[Eight runnable form-library examples](https://github.com/PerchAnton/refmint/tree/main/examples/form-integrations#readme) show
checksum errors, input preservation and server-side validation with RefMint 1.0.0.
JSON Forms includes React, Vue and Angular. Conform and Superforms also work
without JavaScript. These are external consumer examples, not upstream adoptions
or evidence of faster human entry.
2 changes: 2 additions & 0 deletions examples/form-integrations/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
superforms/.svelte-kit/
superforms/build/
116 changes: 116 additions & 0 deletions examples/form-integrations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Reference fields in eight form libraries

These runnable examples validate an optional public order reference with
**RefMint 1.0.0 from npm**, using each library's own validation hook. JSON Forms
has three renderers, so the eight libraries have ten browser routes.

The narrow use case is a person entering a code from a printed label or message.
A shape-only regular expression accepts the selected one-character typo; the
checksum rejects it before a record lookup. This is useful only when an
application already needs such references. If an order number, UUID, barcode or
existing search works well, keep it. These examples do not show faster human
entry, fewer real-world errors, or adoption by the form-library maintainers.

## Run

Use Node.js 24.22 or newer. Dependencies are isolated from RefMint's root package.
From this directory:

```sh
npm ci --ignore-scripts --no-audit --no-fund
npm run dev
```

Open <http://127.0.0.1:5187/>. For the Superforms example, run in a second terminal:

```sh
npm run dev:superforms
```

Open <http://127.0.0.1:5188/>. Both servers bind only to the local machine. They
use synthetic in-memory records and are development examples, not deployable
account or authentication services.

1. Copy the valid code from **Sample order 42** into **Order reference**.
2. Click **Submit reference**. The server returns its canonical lookup key.
3. Change the last character to the selected typo shown on the page and submit.
4. The field shows an error and keeps the text for correction. Correct it and
submit again. A new edit clears the previous lookup result.

Conform and Superforms also support native form submission with JavaScript
turned off. The other examples need JavaScript to render their forms.

## Integration points

| Library | Example and installed version | Validation hook | Specific lesson |
| --- | --- | --- | --- |
| Vueform | [App.vue](vueform/App.vue), 1.13.13 | `Validator.check` and `msg` | Keep invalid input; show a checksum or namespace error through Vueform's rule interface. |
| AutoForm | [main.tsx](autoform/main.tsx), 5.0.0 / Zod provider 6.0.0 | Zod `superRefine`, React Hook Form field | A schema-generated form can display a semantic error that a string pattern cannot detect. |
| Superforms | [page](superforms/src/routes/+page.svelte), [server action](superforms/src/routes/+page.server.js), 3.1.0 | `zod4Client` and server `superValidate` | Share the validation contract, retain failed input, and still validate a native POST without JavaScript. |
| Conform | [App.tsx](conform/App.tsx), [server](conform/server.tsx), 1.21.3 | Client and server `parseWithZod` | SSR, hydration and native POST use the same field error and raw value. |
| Formwerk | [App.vue](formwerk/App.vue), [field](formwerk/ReferenceField.vue), 0.14.4 | `useForm` schema and `useTextField` | Typed form submission and Reset retain the library's own state handling. |
| Formly | [main.ts](formly/main.ts), 11.2.0 / Angular 22.2.6 | Field validator expression and message | Application-level validation; no custom keyword or dependency in Formly itself. |
| JSON Forms | [React](jsonforms-react/main.tsx), [Vue](jsonforms-vue/App.vue), [Angular](jsonforms-angular/main.ts), all 3.8.0 | Shared Ajv `order-reference` format | The same schema and fixtures run through three real renderers. Ajv must receive the custom format. |
| Jedison | [main.mjs](jedison/main.mjs), 1.31.1 | Custom constraint returning an `error` | A blocking checksum error, rather than a warning, prevents the invalid lookup. |

These are external consumer recipes. They do not add a dependency to any of the
upstream libraries or change their validators. The Angular examples use JIT
compilation to keep the standalone harness small; a production Angular app
should use its normal build and rendering setup.

## Shared contract

[reference.mjs](shared/reference.mjs) configures `order`, `uint64`, format v1.
The field retains what the person entered. Valid uppercase, grouped text can be
normalized by the server to the canonical lowercase reference. Requests carry
the raw string; the server validates it again before using the decoded value.

| Input | Result |
| --- | --- |
| Empty, malformed, wrong namespace or selected checksum typo | Field error; no record lookup |
| Valid code for sample 42 | Canonical reference and synthetic record |
| Valid code for unknown sample 43 | Not found; checksum validity does not imply existence |
| Valid code for restricted sample 44 | Forbidden; checksum validity does not imply authorization |

[Ajv configuration](shared/ajv.mjs) and the Zod schema call the same diagnostic
function. The JSON Schema `format` name alone does not install validation. A
plain regular expression checks presentation only, not the Bech32m checksum.

Keep database IDs, regulated invoice numbers and authorization rules intact.
An alias needs storage, uniqueness, lookup and lifecycle rules. Encoding an
existing integer reveals that integer; it is not an access token or encryption.
The fixed demo principal illustrates a separate authorization decision. A real
server must obtain its principal from its own trusted authentication layer.

## Checks

```sh
npm run test:contracts
npm run build
npx playwright install chromium
npm test
```

For an already installed Chromium-compatible browser, set `REFMINT_TEST_CHROME`
to its executable path instead of installing another browser. The lockfile pins
all package versions. `npm test` starts and stops both local servers itself;
close manually started servers on these ports first.

The browser suite uses one worker and **zero retries**. It checks all ten routes:
invalid input, correction, namespace rejection, clearing stale results and real
clipboard paste. It also checks the two Reset controls, both native POST flows
without JavaScript, and direct API requests that bypass client validation.
Contract tests cover invalid types, shape-vs-checksum behavior, shared Ajv/Zod
fixtures and separate not-found/authorization results.

The build compiles the eight Vite pages and the Superforms server bundle. Conform
SSR is exercised by browser tests through Vite's development server; this is not
a Conform production deployment recipe. The form examples' CI job runs Chromium;
there is no claim of Firefox, WebKit, screen-reader, production-load or human
usability coverage for these examples. Clipboard automation is a functional
check, not a participant study. Layout reserves space for field errors so a
message disappearing on blur does not move the Submit button during a click.

No fixture changes the frozen v1 format, the package API, historical performance
measurements or participant results. These files are excluded from the published
runtime package; all framework dependencies belong to this example directory.
1 change: 1 addition & 0 deletions examples/form-integrations/autoform/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>autoform · RefMint</title><link rel="stylesheet" href="/shared/style.css"></head><body><a href="/">All examples</a><h1>autoform</h1><p>Enter or paste the code from the sample card. Submit, then try the one-character typo and correct it.</p><section class="card"><strong>Sample order 42</strong><p class="sample-code">ORDER_1PQP2-AJN2-EY</p><p>Selected typo: <code>ORDER_1PQP2-AJN2-EQ</code></p><p class="hint">Both strings match the example's shape regex. Only the original passes the checksum. This is a code check, not a study of human speed or accuracy.</p></section><main id="app"></main><script type="module" src="/autoform/main.tsx"></script></body></html>
68 changes: 68 additions & 0 deletions examples/form-integrations/autoform/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import { AutoForm } from "@autoform/react/react-hook-form";
import { ZodProvider } from "@autoform/zod";
import { useController } from "react-hook-form";
import { schema, submitReference } from "../shared/reference.mjs";
function ReferenceField({ id, inputProps, error }) {
const { field } = useController({ name: id });
return (
<input
{...inputProps}
{...field}
id={id}
value={field.value ?? ""}
aria-invalid={!!error}
/>
);
}
const Wrapper = ({ children }) => <div>{children}</div>;
const uiComponents = {
Form: (props) => <form {...props} noValidate />,
FieldWrapper: ({ children, error, id }) => (
<div className="reference-field">
<label htmlFor={id}>Order reference</label>
{children}
{error && <p role="alert">{error}</p>}
</div>
),
ErrorMessage: ({ error }) => <p role="alert">{error}</p>,
SubmitButton: () => <button type="submit">Submit reference</button>,
ObjectWrapper: Wrapper,
ArrayWrapper: Wrapper,
ArrayElementWrapper: Wrapper,
};
const provider = new ZodProvider(schema);
function App() {
const [result, setResult] = useState(null);
const [epoch, setEpoch] = useState(0);
return (
<>
<div onInput={() => setResult(null)}>
<AutoForm
key={epoch}
schema={provider}
uiComponents={uiComponents}
formComponents={{ string: ReferenceField }}
defaultValues={{ reference: "" }}
withSubmit
onSubmit={async (values) =>
setResult(await submitReference(values.reference))
}
/>
</div>
<button
onClick={() => {
setEpoch(epoch + 1);
setResult(null);
}}
>
Reset
</button>
<output data-testid="result">
{result?.ok ? result.canonical : result?.error}
</output>
</>
);
}
createRoot(document.getElementById("app")).render(<App />);
44 changes: 44 additions & 0 deletions examples/form-integrations/conform/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React, { useEffect, useState } from "react";
import { useForm, getFormProps, getInputProps } from "@conform-to/react";
import { parseWithZod } from "@conform-to/zod/v4";
import { schema } from "../shared/reference.mjs";
export function App({ lastResult, result }: any) {
const [visibleResult, setVisibleResult] = useState(result);
useEffect(() => {
document.querySelector("main").dataset.ready = "true";
}, []);
const [form, fields] = useForm({
id: "reference-form",
lastResult,
onValidate({ formData }) {
return parseWithZod(formData, { schema });
},
shouldValidate: "onSubmit",
shouldRevalidate: "onInput",
});
return (
<>
<form
onInput={() => setVisibleResult(null)}
method="post"
{...getFormProps(form)}
noValidate
>
<div className="reference-field">
<label htmlFor={fields.reference.id}>Order reference</label>
<input
{...getInputProps(fields.reference, { type: "text" })}
key={fields.reference.key}
/>
<p id={fields.reference.errorId} role="alert">
{fields.reference.errors}
</p>
</div>
<button>Submit reference</button>
</form>
<output data-testid="result">
{visibleResult?.ok ? visibleResult.canonical : visibleResult?.error}
</output>
</>
);
}
7 changes: 7 additions & 0 deletions examples/form-integrations/conform/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from "react";
import { hydrateRoot } from "react-dom/client";
import { App } from "./App";
hydrateRoot(
document.getElementById("app"),
<App {...JSON.parse(document.getElementById("initial-state").textContent)} />,
);
36 changes: 36 additions & 0 deletions examples/form-integrations/conform/server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from "react";
import { renderToString } from "react-dom/server";
import { parseWithZod } from "@conform-to/zod/v4";
import { App } from "./App";
import { schema, lookup } from "../shared/reference.mjs";
import { shell } from "../shared/shell.mjs";
export async function render(req) {
let props: any = {};
let status = 200;
if (req.method === "POST") {
let body = "";
for await (const chunk of req) {
body += chunk;
if (body.length > 8192) return { status: 413, html: "Request too large" };
}
const formData = new FormData();
for (const [key, value] of new URLSearchParams(body))
formData.append(key, value);
const submission = parseWithZod(formData, { schema });
props.lastResult = submission.reply();
if (submission.status === "success") {
props.result = lookup(submission.value.reference);
status = props.result.status;
} else status = 422;
}
const encoded = JSON.stringify(props).replace(/</g, "\\u003c");
return {
status,
html: shell(
"Conform",
renderToString(<App {...props} />),
"/conform/main.tsx",
`<script type="application/json" id="initial-state">${encoded}</script>`,
),
};
}
1 change: 1 addition & 0 deletions examples/form-integrations/formly/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>formly · RefMint</title><link rel="stylesheet" href="/shared/style.css"></head><body><a href="/">All examples</a><h1>formly</h1><p>Enter or paste the code from the sample card. Submit, then try the one-character typo and correct it.</p><section class="card"><strong>Sample order 42</strong><p class="sample-code">ORDER_1PQP2-AJN2-EY</p><p>Selected typo: <code>ORDER_1PQP2-AJN2-EQ</code></p><p class="hint">Both strings match the example's shape regex. Only the original passes the checksum. This is a code check, not a study of human speed or accuracy.</p></section><main id="app"></main><script type="module" src="/formly/main.ts"></script></body></html>
60 changes: 60 additions & 0 deletions examples/form-integrations/formly/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import "zone.js";
import "@angular/compiler";
import {
Component,
importProvidersFrom,
provideZoneChangeDetection,
signal,
} from "@angular/core";
import { bootstrapApplication } from "@angular/platform-browser";
import { ReactiveFormsModule, FormGroup } from "@angular/forms";
import { FormlyModule, FieldType, FormlyFieldConfig } from "@ngx-formly/core";
import { referenceError, submitReference } from "../shared/reference.mjs";
class ReferenceType extends FieldType {}
Component({
selector: "reference-field",
standalone: true,
imports: [ReactiveFormsModule, FormlyModule],
template: `<label [for]="id">Order reference</label><input [id]="id" [formControl]="formControl" [formlyAttributes]="field"/><p role="alert"><formly-validation-message [field]="field"/></p>`,
})(ReferenceType);
class App {
form = new FormGroup({});
model = { reference: "" };
result = signal<any>(null);
fields: FormlyFieldConfig[] = [
{
key: "reference",
type: "reference",
props: { label: "Order reference", required: true },
validation: { show: true },
validators: {
reference: {
expression: (c) => !referenceError(c.value),
message: (_err, field) => referenceError(field.formControl.value),
},
},
},
];
async submit() {
this.form.markAllAsTouched();
if (this.form.valid)
this.result.set(await submitReference(this.model.reference));
}
}
Component({
selector: "form-example",
standalone: true,
imports: [ReactiveFormsModule, FormlyModule],
template: `<form (input)="result.set(null)" [formGroup]="form" (ngSubmit)="submit()" novalidate><div class="reference-field"><formly-form [form]="form" [model]="model" [fields]="fields"/></div><button>Submit reference</button></form><output data-testid="result">{{result()?.ok ? result().canonical : result()?.error}}</output>`,
})(App);
document.getElementById("app").innerHTML = "<form-example></form-example>";
bootstrapApplication(App, {
providers: [
provideZoneChangeDetection(),
importProvidersFrom(
FormlyModule.forRoot({
types: [{ name: "reference", component: ReferenceType }],
}),
),
],
});
Loading
Loading