Skip to content

Commit 57e9434

Browse files
committed
docs: add form-level error pattern using __form__ convention
1 parent 74d2b8f commit 57e9434

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

docs-site/docs/examples/validation.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,83 @@ function ServerValidationForm() {
221221
}
222222
```
223223

224+
## Form-Level Errors
225+
226+
Display general errors that don't belong to a specific field (e.g., account locked, general validation failure):
227+
228+
```jsx
229+
import { Form, Field, FormDataProvider } from 'efx-forms';
230+
import { required } from 'efx-forms/validators';
231+
232+
async function submitForm(values) {
233+
const response = await fetch('/api/login', {
234+
method: 'POST',
235+
body: JSON.stringify(values),
236+
});
237+
238+
if (!response.ok) {
239+
const errors = await response.json();
240+
// Use __form__ key for form-level errors
241+
throw {
242+
__form__: 'Account locked. Please contact support.',
243+
email: 'Invalid email or password',
244+
};
245+
}
246+
247+
return { success: true };
248+
}
249+
250+
function FormLevelErrorForm() {
251+
return (
252+
<Form
253+
name="login-form"
254+
validators={{
255+
email: [required(), email()],
256+
password: [required()],
257+
}}
258+
onSubmit={submitForm}
259+
>
260+
{/* Form-level error display */}
261+
<FormDataProvider>
262+
{({ error }) => {
263+
const formError = error.__form__;
264+
return formError ? (
265+
<div className="form-error" style={{ color: 'red', marginBottom: 16 }}>
266+
{formError}
267+
</div>
268+
) : null;
269+
}}
270+
</FormDataProvider>
271+
272+
<Field name="email" Field={Input} label="Email" type="email" />
273+
<Field name="password" Field={Input} label="Password" type="password" />
274+
<button type="submit">Login</button>
275+
</Form>
276+
);
277+
}
278+
```
279+
280+
**Key Points:**
281+
282+
- Use the reserved `__form__` key in the error object returned from `onSubmit`
283+
- Access via `error.__form__` from `useFormData` or `FormDataProvider`
284+
- Form-level errors coexist with field-specific errors
285+
- Clear form-level errors by returning successfully from `onSubmit`
286+
287+
```jsx
288+
// Example: Multiple error types together
289+
throw {
290+
__form__: 'Submission failed. Please review the errors below.',
291+
email: 'Email already registered',
292+
password: 'Password too weak',
293+
};
294+
295+
// Access in component
296+
const { error } = useFormData();
297+
const formError = error.__form__; // "Submission failed..."
298+
const emailError = error.email; // "Email already registered"
299+
```
300+
224301
## Cross-Field Validation
225302

226303
Validate based on other field values:

0 commit comments

Comments
 (0)