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