| 31 | * @publicApi 22.0 |
| 32 | */ |
| 33 | export function min<TValue extends number | null, TPathKind extends PathKind = PathKind.Root>( |
| 34 | path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, |
| 35 | minValue: number | LogicFn<TValue, number | undefined, TPathKind>, |
| 36 | config?: BaseValidatorConfig<TValue, TPathKind>, |
| 37 | ): void { |
| 38 | const MIN_MEMO = createMetadataKey<number | undefined>(); |
| 39 | |
| 40 | // Memomize the minimum valid. |
| 41 | metadata(path, MIN_MEMO, (ctx) => { |
| 42 | if (config?.when && !config.when(ctx)) { |
| 43 | return undefined; |
| 44 | } |
| 45 | return typeof minValue === 'function' ? minValue(ctx) : minValue; |
| 46 | }); |
| 47 | |
| 48 | // Publish the memoized mininum value for aggregation. |
| 49 | metadata(path, MIN_NUMBER, ({state}) => state.metadata(MIN_MEMO)!()); |
| 50 | |
| 51 | // Use `MIN_NUMBER` to define the `min` property of the field. |
| 52 | metadata(path, MIN, () => MIN_NUMBER as LimitKey<TValue>); |
| 53 | validate(path, (ctx) => { |
| 54 | const value = ctx.value(); |
| 55 | if (value === null || Number.isNaN(value)) { |
| 56 | return undefined; |
| 57 | } |
| 58 | const min = ctx.state.metadata(MIN_MEMO)!(); |
| 59 | if (min === undefined || Number.isNaN(min)) { |
| 60 | return undefined; |
| 61 | } |
| 62 | if (value < min) { |
| 63 | if (config?.error) { |
| 64 | return getOption(config.error, ctx); |
| 65 | } else { |
| 66 | return minError(min, {message: getOption(config?.message, ctx)}); |
| 67 | } |
| 68 | } |
| 69 | return undefined; |
| 70 | }); |
| 71 | } |