| 31 | * @publicApi 22.0 |
| 32 | */ |
| 33 | export function max<TValue extends number | null, TPathKind extends PathKind = PathKind.Root>( |
| 34 | path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, |
| 35 | maxValue: number | LogicFn<TValue, number | undefined, TPathKind>, |
| 36 | config?: BaseValidatorConfig<TValue, TPathKind>, |
| 37 | ): void { |
| 38 | const MAX_MEMO = createMetadataKey<number | undefined>(); |
| 39 | |
| 40 | // Memoize the maximum valid value. |
| 41 | metadata(path, MAX_MEMO, (ctx) => { |
| 42 | if (config?.when && !config.when(ctx)) { |
| 43 | return undefined; |
| 44 | } |
| 45 | return typeof maxValue === 'function' ? maxValue(ctx) : maxValue; |
| 46 | }); |
| 47 | |
| 48 | // Publish the memoized maximum value for aggregation. |
| 49 | metadata(path, MAX_NUMBER, ({state}) => state.metadata(MAX_MEMO)!()); |
| 50 | |
| 51 | // Use `MAX_NUMBER` to define the `max` property of the field. |
| 52 | metadata(path, MAX, () => MAX_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 max = ctx.state.metadata(MAX_MEMO)!(); |
| 59 | if (max === undefined || Number.isNaN(max)) { |
| 60 | return undefined; |
| 61 | } |
| 62 | if (value > max) { |
| 63 | if (config?.error) { |
| 64 | return getOption(config.error, ctx); |
| 65 | } else { |
| 66 | return maxError(max, {message: getOption(config?.message, ctx)}); |
| 67 | } |
| 68 | } |
| 69 | return undefined; |
| 70 | }); |
| 71 | } |