| 41 | * @publicApi 22.0 |
| 42 | */ |
| 43 | export function required<TValue, TPathKind extends PathKind = PathKind.Root>( |
| 44 | path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, |
| 45 | config?: BaseValidatorConfig<TValue, TPathKind> & { |
| 46 | when?: NoInfer<LogicFn<TValue, boolean, TPathKind>>; |
| 47 | }, |
| 48 | ): void { |
| 49 | const REQUIRED_MEMO = metadata(path, createMetadataKey<boolean>(), (ctx) => |
| 50 | config?.when ? config.when(ctx) : true, |
| 51 | ); |
| 52 | metadata(path, REQUIRED, ({state}) => state.metadata(REQUIRED_MEMO)!()!); |
| 53 | validate(path, (ctx) => { |
| 54 | if (ctx.state.metadata(REQUIRED_MEMO)!() && isEmpty(ctx.value())) { |
| 55 | if (config?.error) { |
| 56 | return getOption(config.error, ctx); |
| 57 | } else { |
| 58 | return requiredError({message: getOption(config?.message, ctx)}); |
| 59 | } |
| 60 | } |
| 61 | return undefined; |
| 62 | }); |
| 63 | } |