/
optional.ts
48 lines (46 loc) · 1.14 KB
/
optional.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { RuleOptions, Validator, Validation, Values } from "../index.d";
import { toErrorMessage } from "../helpers";
/**
* Make the validator optional. To be optional, the value must be either an
* empty string or `null`.
*
* @example
* ```ts
* useForm(({ optional, regex }) => ({
* email: [ optional(regex(/^\S+@\S+$/)) ]
* }));
* ```
*
* @param {Validator} validator The optional validator.
* @param {RuleOptions} options The validation options.
* @return {Validator} The validation object.
*/
export function optional<Params>(
validator: Validator<Params>,
options?: RuleOptions,
): Validator<Params> {
return (
attribute: string,
input: any,
values: Values<Params>,
): Validation<Params> => {
const result = validator(attribute, input, values);
return {
valid: ["", undefined].includes(input) || result.valid,
type: options?.type || result.type,
optional: true,
input,
args: [],
values,
message: toErrorMessage({
defaultMessage: result.message,
args: [],
input,
values,
attribute,
options,
}),
attribute,
};
};
}