( path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, maxDateValue: Date | LogicFn<TValue, Date | undefined, TPathKind>, config?: BaseValidatorConfig<TValue, TPathKind>, )
| 30 | * @publicApi 22.0 |
| 31 | */ |
| 32 | export function maxDate<TValue extends Date | null, TPathKind extends PathKind = PathKind.Root>( |
| 33 | path: SchemaPath<TValue, SchemaPathRules.Supported, TPathKind>, |
| 34 | maxDateValue: Date | LogicFn<TValue, Date | undefined, TPathKind>, |
| 35 | config?: BaseValidatorConfig<TValue, TPathKind>, |
| 36 | ): void { |
| 37 | const MAX_MEMO = createMetadataKey<Date | undefined>(); |
| 38 | |
| 39 | // Memoize the maximum valid date. |
| 40 | metadata(path, MAX_MEMO, (ctx) => { |
| 41 | if (config?.when && !config.when(ctx)) { |
| 42 | return undefined; |
| 43 | } |
| 44 | return typeof maxDateValue === 'function' ? maxDateValue(ctx) : maxDateValue; |
| 45 | }); |
| 46 | |
| 47 | // Publish the memoized maximum date for aggregation. |
| 48 | metadata(path, MAX_DATE, ({state}) => state.metadata(MAX_MEMO)!()); |
| 49 | |
| 50 | // Use `MAX_DATE` to define the `max` property of the field. |
| 51 | metadata(path, MAX, () => MAX_DATE as LimitKey<TValue>); |
| 52 | |
| 53 | // Validate that the field value is not greater than the maximum date. |
| 54 | validate(path, (ctx) => { |
| 55 | const value = ctx.value(); |
| 56 | if (value === null || Number.isNaN(value.getTime())) { |
| 57 | return undefined; |
| 58 | } |
| 59 | const max = ctx.state.metadata(MAX_MEMO)!(); |
| 60 | if (max === undefined || Number.isNaN(max.getTime())) { |
| 61 | return undefined; |
| 62 | } |
| 63 | if (value > max) { |
| 64 | if (config?.error) { |
| 65 | return getOption(config.error, ctx); |
| 66 | } else { |
| 67 | return maxDateError(max, {message: getOption(config?.message, ctx)}); |
| 68 | } |
| 69 | } |
| 70 | return undefined; |
| 71 | }); |
| 72 | } |
no test coverage detected
searching dependent graphs…