Skip to content

Commit b58a905

Browse files
committed
Added signature to set a form-level error with setError.
1 parent fc0a31f commit b58a905

File tree

3 files changed

+61
-9
lines changed

3 files changed

+61
-9
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ Headlines: Added, Changed, Deprecated, Removed, Fixed, Security
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased]
9+
10+
### Added
11+
12+
- Added signature to more conveniently set a form-level error with `setError`.
13+
814
## [1.1.3] - 2023-06-29
915

1016
### Fixed

src/errors.test.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ describe('Errors', async () => {
2222
expect(output.data.name).toBeNull();
2323

2424
const err = {
25-
_errors: ['Form-level error'],
25+
_errors: ['Form-level error', 'Second form-level error'],
2626
scopeId: ['This is an error'],
2727
enumber: ['This should be ok', 'Still ok'],
2828
arr: { _errors: ['Array-level error'], 3: ['Array item error'] },
@@ -37,7 +37,8 @@ describe('Errors', async () => {
3737
setError(output, 'enumber', 'Still ok');
3838
setError(output, 'arr._errors', 'Array-level error');
3939
setError(output, '', 'Form-level error that should not be displayed.');
40-
setError(output, '', 'Form-level error', { overwrite: true });
40+
setError(output, 'Form-level error', { overwrite: true });
41+
setError(output, 'Second form-level error');
4142

4243
assert(!output.valid);
4344
expect(output.errors).toStrictEqual(err);

src/lib/superValidate.ts

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { fail, json, type RequestEvent } from '@sveltejs/kit';
1+
import { ActionFailure, fail, json, type RequestEvent } from '@sveltejs/kit';
22
import { parse, stringify } from 'devalue';
33
import {
44
SuperFormError,
@@ -55,19 +55,64 @@ export function message<T extends ZodValidation<AnyZodObject>, M>(
5555

5656
export const setMessage = message;
5757

58+
type SetErrorOptions = {
59+
overwrite?: boolean;
60+
status?: NumericRange<400, 599>;
61+
};
62+
63+
/**
64+
* Sets a form-level error.
65+
* form.valid is automatically set to false.
66+
*
67+
* @param {SuperValidated<T, unknown>} form A validation object, usually returned from superValidate.
68+
* @param {string | string[]} error Error message(s).
69+
* @param {SetErrorOptions} options Option to overwrite previous errors and set a different status than 400. The status must be in the range 400-599.
70+
* @returns fail(status, { form })
71+
*/
72+
export function setError<T extends ZodValidation<AnyZodObject>>(
73+
form: SuperValidated<T, unknown>,
74+
error: string | string[],
75+
options?: SetErrorOptions
76+
): ActionFailure<{ form: SuperValidated<T, unknown> }>;
77+
5878
/**
59-
* Sets an error for a form field, with an optional HTTP status code.
60-
* form.valid is automatically set to false. A status lower than 400 cannot be sent.
79+
* Sets an error for a form field or array field.
80+
* form.valid is automatically set to false.
81+
*
82+
* @param {SuperValidated<T, unknown>} form A validation object, usually returned from superValidate.
83+
* @param {'' | StringPathLeaves<z.infer<UnwrapEffects<T>>, '_errors'>} path Path to the form field. Use an empty string to set a form-level error. Array-level errors can be set by appending "._errors" to the field.
84+
* @param {string | string[]} error Error message(s).
85+
* @param {SetErrorOptions} options Option to overwrite previous errors and set a different status than 400. The status must be in the range 400-599.
86+
* @returns fail(status, { form })
6187
*/
6288
export function setError<T extends ZodValidation<AnyZodObject>>(
6389
form: SuperValidated<T, unknown>,
6490
path: '' | StringPathLeaves<z.infer<UnwrapEffects<T>>, '_errors'>,
6591
error: string | string[],
66-
options: { overwrite?: boolean; status?: NumericRange<400, 599> } = {
67-
overwrite: false,
68-
status: 400
92+
options?: SetErrorOptions
93+
): ActionFailure<{ form: SuperValidated<T, unknown> }>;
94+
95+
export function setError<T extends ZodValidation<AnyZodObject>>(
96+
form: SuperValidated<T, unknown>,
97+
path:
98+
| string
99+
| string[]
100+
| (string & StringPathLeaves<z.infer<UnwrapEffects<T>>, '_errors'>),
101+
error?: string | string[] | SetErrorOptions,
102+
options?: SetErrorOptions
103+
): ActionFailure<{ form: SuperValidated<T, unknown> }> {
104+
// Unify signatures
105+
if (
106+
error == undefined ||
107+
(typeof error !== 'string' && !Array.isArray(error))
108+
) {
109+
options = error;
110+
error = path;
111+
path = '';
69112
}
70-
) {
113+
114+
if (options === undefined) options = {};
115+
71116
const errArr = Array.isArray(error) ? error : [error];
72117

73118
if (!form.errors) form.errors = {};

0 commit comments

Comments
 (0)