@regle/rules 1.1.0-beta.2 → 1.1.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,462 +0,0 @@
1
- import { RegleRuleMetadataDefinition, RegleRuleWithParamsDefinition, RegleRuleDefinitionWithMetadataProcessor, RegleRuleMetadataConsumer, RegleRuleDefinition, InlineRuleDeclaration, UnwrapRegleUniversalParams, Maybe, FormRuleDeclaration, CommonComparationOptions } from '@regle/core';
2
- import { Ref, MaybeRefOrGetter, MaybeRef } from 'vue';
3
-
4
- /**
5
- * The withMessage wrapper lets you associate an error message with a rule. Pass your rule as the first argument and the error message as the second.
6
- *
7
- * ```ts
8
- * const { r$ } = useRegle({ name: '' }, {
9
- name: {
10
- customRule1: withMessage((value) => !!value, "Custom Error"),
11
- customRule2: withMessage(customRuleInlineWithMetaData, "Custom Error"),
12
- customRule3: withMessage(
13
- customRuleInlineWithMetaData,
14
- ({ $value, foo }) => `Custom Error: ${$value} ${foo}`
15
- ),
16
- }
17
- })
18
- * ```
19
- * Docs: {@link https://reglejs.dev/core-concepts/rules/rule-wrappers#withmessage}
20
- */
21
- declare function withMessage<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>, newMessage: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TMetadata>, string | string[]>): RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>;
22
- declare function withMessage<TValue extends any, TParams extends unknown[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>, newMessage: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TMetadata>, string | string[]>): RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>;
23
- declare function withMessage<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: InlineRuleDeclaration<TValue, TParams, TReturn>, newMessage: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TReturn extends Promise<infer M> ? M : TReturn>, string | string[]>): RegleRuleDefinition<TValue, TParams, TAsync, TReturn extends Promise<infer M> ? M : TReturn>;
24
-
25
- /**
26
- * The withTooltip wrapper allows you to display additional messages for your field that aren’t necessarily errors. Tooltips are aggregated and accessible via $fields.xxx.$tooltips .
27
- */
28
- declare function withTooltip<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>, newTooltip: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TMetadata>, string | string[]>): RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>;
29
- declare function withTooltip<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>, newTooltip: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TMetadata>, string | string[]>): RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>;
30
- declare function withTooltip<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: InlineRuleDeclaration<TValue, TParams, TReturn>, newTooltip: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TReturn extends Promise<infer M> ? M : TReturn>, string | string[]>): RegleRuleDefinition<TValue, TParams, TAsync, TReturn extends Promise<infer M> ? M : TReturn>;
31
-
32
- /**
33
- * withAsync works like withParams, but is specifically designed for async rules that depend on external values.
34
- *
35
- * ```ts
36
- *import { withAsync } from '@regle/rules';
37
-
38
- const base = ref('foo');
39
-
40
- const { r$ } = useRegle({ name: '' }, {
41
- name: {
42
- customRule: withAsync(async (value, param) => {
43
- await someAsyncCall(param)
44
- }, [base])
45
- }
46
- })
47
- * ```
48
- * Docs: {@link https://reglejs.dev/core-concepts/rules/rule-wrappers#withasync}
49
- */
50
- declare function withAsync<TValue, TParams extends (Ref<unknown> | (() => unknown))[] = [], TReturn extends Promise<RegleRuleMetadataDefinition> = Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn>(rule: InlineRuleDeclaration<TValue, TParams, TReturn>, depsArray?: [...TParams]): RegleRuleDefinition<TValue, UnwrapRegleUniversalParams<TParams>, true, TMetadata>;
51
- declare function withAsync<TValue extends any, TParams extends any[], TMetadata extends RegleRuleMetadataDefinition>(rule: RegleRuleWithParamsDefinition<TValue, TParams, true, TMetadata>, depsArray?: [...TParams]): RegleRuleWithParamsDefinition<TValue, TParams, true, TMetadata>;
52
-
53
- /**
54
- * The withParams wrapper allows your rule to depend on external parameters, such as a reactive property in your component or store.
55
- *
56
- * By default, useRegle observes changes automatically when rules are defined using getter functions or computed properties.
57
- *
58
- * ```ts
59
- * import { withParams } from '@regle/rules';
60
-
61
- const base = ref('foo');
62
-
63
- const { r$ } = useRegle({ name: '' }, {
64
- name: {
65
- customRule: withParams((value, param) => value === param, [base]),
66
- // or
67
- customRule: withParams((value, param) => value === param, [() => base.value]),
68
- }
69
- })
70
- * ```
71
- * Docs: {@link https://reglejs.dev/core-concepts/rules/rule-wrappers#withparams}
72
- */
73
- declare function withParams<TValue, TParams extends (Ref<unknown> | (() => unknown))[] = [], TReturn extends RegleRuleMetadataDefinition = RegleRuleMetadataDefinition, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: InlineRuleDeclaration<TValue, TParams, TReturn> | RegleRuleDefinition<TValue, any[], TAsync, TMetadata>, depsArray: [...TParams]): RegleRuleDefinition<TValue, UnwrapRegleUniversalParams<TParams>, TAsync, TMetadata>;
74
- declare function withParams<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition = RegleRuleMetadataDefinition, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>, depsArray: [...TParams]): RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetadata>;
75
-
76
- /**
77
- * The applyIf operator is similar to requiredIf, but it can be used with any rule. It simplifies conditional rule declarations.
78
- */
79
- declare function applyIf<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(_condition: MaybeRefOrGetter<Maybe<boolean>>, rule: InlineRuleDeclaration<TValue, TParams, TReturn> | RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>): RegleRuleDefinition<TValue, [...TParams, condition: boolean], TAsync, TMetadata>;
80
-
81
- /**
82
- * This is almost a must have for optional fields. It checks if any value you provided is defined (including arrays and objects). You can base your validator result on this.
83
- *
84
- * isFilled also acts as a type guard.
85
- *
86
- * @param value - the target value
87
- * @param [considerEmptyArrayInvalid=true] - will return true if set to `false`. (default: `true`)
88
- */
89
- declare function isFilled<T extends unknown>(value: T, considerEmptyArrayInvalid?: boolean): value is NonNullable<T>;
90
-
91
- /**
92
- * This is a type guard that will check if the passed value is a real Number. This also returns false for NaN, so this is better than typeof value === "number".
93
- */
94
- declare function isNumber(value: unknown): value is number;
95
-
96
- /**
97
- * This utility can take multiple regular expressions as arguments. It checks the input's validity and tests it against the provided regex patterns.
98
- */
99
- declare function matchRegex(_value: string | number | null | undefined, ...expr: RegExp[]): boolean;
100
-
101
- /**
102
- * This helper will return the length of any data type you pass. It works with strings, arrays, objects and numbers.
103
- */
104
- declare function getSize(value: MaybeRef<string | any[] | Record<string, any> | number>): number;
105
-
106
- /**
107
- * This utility converts any string (or number) into a number using the Number constructor.
108
- *
109
- * @returns ⚠️ Warning, returned value can be NaN
110
- */
111
- declare function toNumber<T extends number | string | undefined>(argument: T): number;
112
-
113
- declare global {
114
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
115
- interface SymbolConstructor {
116
- readonly observable: symbol;
117
- }
118
- }
119
-
120
- declare const emptyObjectSymbol$1: unique symbol;
121
-
122
- /**
123
- Represents a strictly empty plain object, the `{}` value.
124
-
125
- When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)).
126
-
127
- @example
128
- ```
129
- import type {EmptyObject} from 'type-fest';
130
-
131
- // The following illustrates the problem with `{}`.
132
- const foo1: {} = {}; // Pass
133
- const foo2: {} = []; // Pass
134
- const foo3: {} = 42; // Pass
135
- const foo4: {} = {a: 1}; // Pass
136
-
137
- // With `EmptyObject` only the first case is valid.
138
- const bar1: EmptyObject = {}; // Pass
139
- const bar2: EmptyObject = 42; // Fail
140
- const bar3: EmptyObject = []; // Fail
141
- const bar4: EmptyObject = {a: 1}; // Fail
142
- ```
143
-
144
- Unfortunately, `Record<string, never>`, `Record<keyof any, never>` and `Record<never, never>` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}.
145
-
146
- @category Object
147
- */
148
- type EmptyObject$1 = {[emptyObjectSymbol$1]?: never};
149
-
150
- /**
151
- * This is the inverse of isFilled. It will check if the value is in any way empty (including arrays and objects)
152
- *
153
- * isEmpty also acts as a type guard.
154
- *
155
- * @param value - the target value
156
- * @param [considerEmptyArrayInvalid=true] - will return false if set to `false`. (default: `true`)
157
- */
158
- declare function isEmpty(value: unknown, considerEmptyArrayInvalid?: boolean): value is null | undefined | [] | EmptyObject$1;
159
-
160
- /**
161
- * This is a useful helper that can check if the provided value is a Date, it is used internally for date rules. This can also check strings.
162
- */
163
- declare function isDate(value: unknown): value is Date;
164
-
165
- /**
166
- * This utility will coerce any string, number or Date value into a Date using the Date constructor.
167
- */
168
- declare function toDate(argument: Maybe<Date | number | string>): Date;
169
-
170
- declare global {
171
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
172
- interface SymbolConstructor {
173
- readonly observable: symbol;
174
- }
175
- }
176
-
177
- declare const emptyObjectSymbol: unique symbol;
178
-
179
- /**
180
- Represents a strictly empty plain object, the `{}` value.
181
-
182
- When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)).
183
-
184
- @example
185
- ```
186
- import type {EmptyObject} from 'type-fest';
187
-
188
- // The following illustrates the problem with `{}`.
189
- const foo1: {} = {}; // Pass
190
- const foo2: {} = []; // Pass
191
- const foo3: {} = 42; // Pass
192
- const foo4: {} = {a: 1}; // Pass
193
-
194
- // With `EmptyObject` only the first case is valid.
195
- const bar1: EmptyObject = {}; // Pass
196
- const bar2: EmptyObject = 42; // Fail
197
- const bar3: EmptyObject = []; // Fail
198
- const bar4: EmptyObject = {a: 1}; // Fail
199
- ```
200
-
201
- Unfortunately, `Record<string, never>`, `Record<keyof any, never>` and `Record<never, never>` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}.
202
-
203
- @category Object
204
- */
205
- type EmptyObject = {[emptyObjectSymbol]?: never};
206
-
207
- type ExtractValueFromRules<T extends any[]> = T extends [infer F, ...infer R] ? F extends RegleRuleDefinition<infer V, any, any, any> ? [V, ...ExtractValueFromRules<R>] : F extends InlineRuleDeclaration<infer V, any> ? [V, ...ExtractValueFromRules<R>] : [F, ...ExtractValueFromRules<R>] : [];
208
- type ExtractAsyncStatesFromRules<T extends any[]> = T extends [infer F, ...infer R] ? F extends RegleRuleDefinition<any, any, infer A, any> ? [A, ...ExtractValueFromRules<R>] : F extends InlineRuleDeclaration<any, any> ? [ReturnType<F> extends Promise<any> ? true : false, ...ExtractValueFromRules<R>] : [F, ...ExtractValueFromRules<R>] : [];
209
- type ExtractAsync<T extends [...any[]]> = T extends [infer F, ...infer R] ? F extends true ? true : F extends false ? ExtractAsync<R> : false : false;
210
- type GuessAsyncFromRules<T extends any[]> = ExtractAsync<ExtractAsyncStatesFromRules<T>>;
211
- type ExtractParamsFromRules<T extends any[]> = T extends [infer F, ...infer R] ? F extends RegleRuleDefinition<any, infer P, any, any> ? [P, ...ExtractParamsFromRules<R>] : [F, ...ExtractParamsFromRules<R>] : [];
212
- type MetadataBase = {
213
- $valid: boolean;
214
- [x: string]: any;
215
- };
216
- type ExtractMetaDataFromRules<T extends any[]> = T extends [infer F, ...infer R] ? F extends RegleRuleDefinition<any, any, any, infer M extends MetadataBase> ? [M, ...ExtractMetaDataFromRules<R>] : F extends InlineRuleDeclaration<any, any[], infer M extends MetadataBase | Promise<MetadataBase>> ? [M, ...ExtractMetaDataFromRules<R>] : [...ExtractMetaDataFromRules<R>] : [];
217
- type ExtractMetadata<T extends [...any[]]> = T extends [infer F, ...infer R] ? F & ExtractMetadata<R> : {};
218
- type GuessMetadataFromRules<T extends any[], TMeta = ExtractMetadata<ExtractMetaDataFromRules<T>>> = TMeta extends EmptyObject ? boolean : TMeta;
219
- type FilterTuple<T extends any[]> = T extends [infer F, ...infer R] ? [F] extends [[]] ? [...FilterTuple<R>] : [F, ...FilterTuple<R>] : [];
220
- type UnwrapTuples<T extends any[]> = FilterTuple<T> extends [infer U extends any[]] ? U : FilterTuple<T>;
221
-
222
- /**
223
- * The and operator combines multiple rules and validates successfully only if all provided rules are valid.
224
- */
225
- declare function and<TRules extends FormRuleDeclaration<any, any>[]>(...rules: [...TRules]): RegleRuleDefinition<ExtractValueFromRules<TRules>[number], UnwrapTuples<ExtractParamsFromRules<TRules>>, GuessAsyncFromRules<TRules>, GuessMetadataFromRules<TRules>>;
226
-
227
- /**
228
- * The or operator validates successfully if at least one of the provided rules is valid.
229
- */
230
- declare function or<TRules extends FormRuleDeclaration<any, any>[]>(...rules: [...TRules]): RegleRuleDefinition<ExtractValueFromRules<TRules>[number], UnwrapTuples<ExtractParamsFromRules<TRules>>, GuessAsyncFromRules<TRules>, GuessMetadataFromRules<TRules>>;
231
-
232
- /**
233
- * The not operator passes when the provided rule fails and fails when the rule passes. It can be combined with other rules.
234
- */
235
- declare function not<TValue, TParams extends any[] = [], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = TReturn extends Promise<any> ? true : false>(rule: RegleRuleDefinition<TValue, TParams, TAsync, TMetadata> | InlineRuleDeclaration<TValue, TParams, TReturn>, message?: RegleRuleDefinitionWithMetadataProcessor<TValue, RegleRuleMetadataConsumer<TValue, TParams, TMetadata>, string | string[]>): RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>;
236
-
237
- /**
238
- * Requires non-empty data. Checks for empty arrays and strings containing only whitespaces.
239
- */
240
- declare const required: RegleRuleDefinition<unknown, [], false, boolean, unknown>;
241
-
242
- /**
243
- * Requires the input value to have a maximum specified length, inclusive. Works with arrays, objects and strings.
244
- *
245
- * @param max - the maximum length
246
- */
247
- declare const maxLength: RegleRuleWithParamsDefinition<string | any[] | Record<PropertyKey, any>, [
248
- count: number,
249
- options?: CommonComparationOptions
250
- ], false, boolean>;
251
-
252
- /**
253
- * Requires non-empty data, only if provided data property, ref, or a function resolves to true.
254
- *
255
- * @param condition - the condition to enable the required rule
256
- */
257
- declare const requiredIf: RegleRuleWithParamsDefinition<unknown, [condition: boolean], false, boolean>;
258
-
259
- /**
260
- * Allows only alphabetic characters.
261
- * */
262
- declare const alpha: RegleRuleDefinition<string, [], false, boolean, string>;
263
-
264
- /**
265
- * Allows only alphanumeric characters.
266
- */
267
- declare const alphaNum: RegleRuleDefinition<string | number, [], false, boolean, string | number>;
268
-
269
- /**
270
- * Checks if a number is in specified bounds. min and max are both inclusive.
271
- *
272
- * @param min - the minimum limit
273
- * @param max - the maximum limit
274
- */
275
- declare const between: RegleRuleWithParamsDefinition<number, [
276
- min: number,
277
- max: number,
278
- options?: CommonComparationOptions
279
- ], false, boolean>;
280
-
281
- /**
282
- * Allows positive and negative decimal numbers.
283
- */
284
- declare const decimal: RegleRuleDefinition<string | number, [], false, boolean, string | number>;
285
-
286
- /**
287
- * Validates email addresses. Always verify on the server to ensure the address is real and not already in use.
288
- */
289
- declare const email: RegleRuleDefinition<string, [], false, boolean, string>;
290
-
291
- /**
292
- * Allows only integers (positive and negative).
293
- */
294
- declare const integer: RegleRuleDefinition<string | number, [], false, boolean, string | number>;
295
-
296
- /**
297
- * Requires a field to have a specified maximum numeric value.
298
- *
299
- * @param max - the maximum value
300
- */
301
- declare const maxValue: RegleRuleWithParamsDefinition<number, [
302
- count: number,
303
- options?: CommonComparationOptions
304
- ], false, boolean>;
305
-
306
- /**
307
- * Requires the input value to have a minimum specified length, inclusive. Works with arrays, objects and strings.
308
- *
309
- * @param min - the minimum value
310
- */
311
- declare const minLength: RegleRuleWithParamsDefinition<string | any[] | Record<PropertyKey, any>, [
312
- count: number,
313
- options?: CommonComparationOptions
314
- ], false, boolean>;
315
-
316
- /**
317
- * Requires a field to have a specified minimum numeric value.
318
- *
319
- * @param count - the minimum count
320
- */
321
- declare const minValue: RegleRuleWithParamsDefinition<number, [
322
- count: number,
323
- options?: CommonComparationOptions
324
- ], false, boolean>;
325
-
326
- declare const exactValue: RegleRuleWithParamsDefinition<number, [count: number], false, boolean>;
327
-
328
- /**
329
- * Requires the input value to have a strict specified length, inclusive. Works with arrays, objects and strings.
330
- *
331
- * @param count - the required length
332
- */
333
- declare const exactLength: RegleRuleWithParamsDefinition<string | any[] | Record<PropertyKey, any>, [
334
- count: number
335
- ], false, boolean>;
336
-
337
- /**
338
- * Allows only numeric values (including numeric strings).
339
- */
340
- declare const numeric: RegleRuleDefinition<string | number, [], false, boolean, string | number>;
341
-
342
- /**
343
- * Requires non-empty data, only if provided data property, ref, or a function resolves to false.
344
- *
345
- * @param condition - the condition to disable the required rule
346
- */
347
- declare const requiredUnless: RegleRuleWithParamsDefinition<unknown, [condition: boolean], false, boolean>;
348
-
349
- /**
350
- * Checks if the value matches the specified property or ref.
351
- */
352
- declare const sameAs: RegleRuleWithParamsDefinition<unknown, [target: unknown, otherName?: string], false, boolean>;
353
-
354
- /**
355
- * Validates URLs.
356
- */
357
- declare const url: RegleRuleDefinition<string, [], false, boolean, string>;
358
-
359
- /**
360
- * Checks if the date is after the given parameter.
361
- *
362
- * @param after - the date to compare to
363
- */
364
- declare const dateAfter: RegleRuleWithParamsDefinition<string | Date, [
365
- after: Maybe<string | Date>
366
- ], false, true | {
367
- $valid: false;
368
- error: 'date-not-after';
369
- } | {
370
- $valid: false;
371
- error: 'value-or-paramater-not-a-date';
372
- }>;
373
-
374
- /**
375
- * Checks if the date is before the given parameter.
376
- *
377
- * @param before - the date to compare to
378
- */
379
- declare const dateBefore: RegleRuleWithParamsDefinition<string | Date, [
380
- before: Maybe<string | Date>
381
- ], false, true | {
382
- $valid: false;
383
- error: 'date-not-before';
384
- } | {
385
- $valid: false;
386
- error: 'value-or-paramater-not-a-date';
387
- }>;
388
-
389
- /**
390
- * Checks if the date falls between the specified bounds.
391
- *
392
- * @param before - the minimum limit
393
- * @param after - the maximum limit
394
- */
395
- declare const dateBetween: RegleRuleWithParamsDefinition<string | Date, [
396
- before: Maybe<string | Date>,
397
- after: Maybe<string | Date>
398
- ], false, boolean>;
399
-
400
- /**
401
- * Validates IPv4 addresses in dotted decimal notation 127.0.0.1.
402
- */
403
- declare const ipAddress: RegleRuleDefinition<string, [], false, boolean, string>;
404
-
405
- /**
406
- * Validates MAC addresses. Call as a function to specify a custom separator (e.g., ':' or an empty string for 00ff1122334455).
407
- *
408
- * @param separator - the custom separator
409
- */
410
- declare const macAddress: RegleRuleWithParamsDefinition<string, [separator?: string | undefined], false, boolean>;
411
-
412
- /**
413
- * Requires a boolean value to be true. This is useful for checkbox inputs.
414
- */
415
- declare const checked: RegleRuleDefinition<boolean, [], false, boolean, boolean>;
416
-
417
- /**
418
- * Checks if the string contains the specified substring.
419
- *
420
- * @param part - the part the value needs to contain
421
- */
422
- declare const contains: RegleRuleWithParamsDefinition<string, [part: Maybe<string>], false, boolean>;
423
-
424
- /**
425
- * Checks if the string starts with the specified substring.
426
- *
427
- * @private part - the vlaue the field must start with
428
- */
429
- declare const startsWith: RegleRuleWithParamsDefinition<string, [part: Maybe<string>], false, boolean>;
430
-
431
- /**
432
- * Checks if the string ends with the specified substring.
433
- *
434
- * @param part - the value the field must end with
435
- */
436
- declare const endsWith: RegleRuleWithParamsDefinition<string, [part: Maybe<string>], false, boolean>;
437
-
438
- /**
439
- * Checks if the value matches one or more regular expressions.
440
- */
441
- declare const regex: RegleRuleWithParamsDefinition<string | number, [regexp: RegExp | RegExp[]], false, boolean>;
442
-
443
- /**
444
- * Allow only one of the values from a fixed Array of possible entries.
445
- */
446
- declare function oneOf<const TValues extends [string | number, ...(string | number)[]]>(options: MaybeRefOrGetter<[...TValues]>): RegleRuleDefinition<TValues[number], [options: TValues], false, boolean, string | number>;
447
-
448
- type EnumLike = {
449
- [k: string]: string | number;
450
- [nu: number]: string;
451
- };
452
- /**
453
- * Validate against a native Typescript enum value.
454
- */
455
- declare function nativeEnum<T extends EnumLike>(enumLike: T): RegleRuleDefinition<T[keyof T], [enumLike: T], false, boolean, string | number>;
456
-
457
- /**
458
- * Allow only one possible literal value
459
- */
460
- declare function literal<const TValue extends string | number>(literal: MaybeRefOrGetter<TValue>): RegleRuleDefinition<TValue, [literal: TValue], false, boolean, string | number>;
461
-
462
- export { type EnumLike, alpha, alphaNum, and, applyIf, between, checked, contains, dateAfter, dateBefore, dateBetween, decimal, email, endsWith, exactLength, exactValue, getSize, integer, ipAddress, isDate, isEmpty, isFilled, isNumber, literal, macAddress, matchRegex, maxLength, maxValue, minLength, minValue, nativeEnum, not, numeric, oneOf, or, regex, required, requiredIf, requiredUnless, sameAs, startsWith, toDate, toNumber, url, withAsync, withMessage, withParams, withTooltip };
@@ -1 +0,0 @@
1
- 'use strict';var core=require('@regle/core'),vue=require('vue');function h(e,t){let r,n,s,R;typeof e=="function"&&!("_validator"in e)?(r=core.InternalRuleType.Inline,n=e):{_type:r,validator:n,_active:s,_params:R}=e;let l=core.createRule({type:r,validator:n,active:s,message:t}),u=[...R??[]];if(l._params=u,l._message_patched=true,typeof l=="function"){let a=l(...u);return a._message_patched=true,a}else return l}function _(e,t){let r,n,s,R,l;typeof e=="function"&&!("_validator"in e)?(r=core.InternalRuleType.Inline,n=e):{_type:r,validator:n,_active:s,_params:R,_message:l}=e;let u=core.createRule({type:r,validator:n,active:s,message:l,tooltip:t}),a=[...R??[]];if(u._params=a,u._tooltip_patched=true,typeof u=="function"){let m=u(...a);return u._tooltip_patched=true,m}else return u}function E(e,t){let r,n,s=[],R="";typeof e=="function"?(r=core.InternalRuleType.Inline,n=async(u,...a)=>e(u,...a),s=[t]):({_type:r,_message:R}=e,s=s=e._params?.concat(t),n=async(...u)=>e.validator(u));let l=core.createRule({type:core.InternalRuleType.Async,validator:n,message:R});return l._params=l._params?.concat(s),l(...t??[])}function P(e,t){let r,n,s=[],R="";typeof e=="function"?(r=core.InternalRuleType.Inline,n=(u,...a)=>e(u,...a),s=[t]):({_type:r,validator:n,_message:R}=e,s=s=e._params?.concat(t));let l=core.createRule({type:core.InternalRuleType.Inline,validator:n,message:R});return l._params=l._params?.concat(s),l(...t)}function L(e,t){let r,n,s=[],R="";typeof t=="function"?(r=core.InternalRuleType.Inline,n=t,s=[e]):({_type:r,validator:n,_message:R}=t,s=t._params?.concat([e]));function l(o,...p){let[b]=core.unwrapRuleParameters([e]);return b?n(o,...p):true}function u(o){let[p]=core.unwrapRuleParameters([e]);return p}let a=core.createRule({type:r,validator:l,active:u,message:R}),m=[...s??[]];return a._params=m,typeof a=="function"?a(...m):a}function f(e,t=true){return e==null?true:e instanceof Date?isNaN(e.getTime()):e.constructor.name=="File"||e.constructor.name=="FileList"?e.size<=0:Array.isArray(e)?t?e.length===0:false:typeof e=="object"&&e!=null?Object.keys(e).length===0:!String(e).length}function x(e){if(f(e))return false;try{let t=null;if(e instanceof Date)t=e;else if(typeof e=="string"){let r=new Date(e);if(r.toString()==="Invalid Date")return !1;t=r;}return !!t}catch{return false}}function T(e){let t=Object.prototype.toString.call(e);return e==null?new Date(NaN):e instanceof Date||typeof e=="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function i(e,t=true){return !f(typeof e=="string"?e.trim():e,t)}function y(e){return e==null||typeof e!="number"?false:!isNaN(e)}function g(e,...t){if(f(e))return true;let r=typeof e=="number"?e.toString():e;return t.every(n=>(n.lastIndex=0,n.test(r)))}function D(e){let t=vue.unref(e);return Array.isArray(t)?t.length:typeof t=="object"?Object.keys(t).length:typeof t=="number"?isNaN(t)?0:t:String(t).length}function c(e){return typeof e=="number"?e:e!=null?typeof e=="string"?e.trim()!==e?NaN:+e:NaN:NaN}function q(...e){let t=e.some(a=>typeof a=="function"?a.constructor.name==="AsyncFunction":a._async),r=e.map(a=>{if(typeof a=="function")return null;{let m=a._params;return m?.length?m:[]}}).flat().filter(a=>!!a);function n(a,m,...o){let p=[],b=0;for(let d of a)if(typeof d=="function")p.push(d(m)),b++;else {let M=d._params?.length??0;p.push(d.validator(m,...o.slice(b,M))),M&&(b+=M);}return p}function s(a){return a?.some(o=>typeof o!="boolean")?{$valid:a.every(o=>typeof o=="boolean"?!!o:o.$valid),...a.reduce((o,p)=>{if(typeof p=="boolean")return o;let{$valid:b,...d}=p;return {...o,...d}},{})}:a.every(o=>!!o)}let R;e.length?R=t?async(a,...m)=>{let o=await Promise.all(n(e,a,...m));return s(o)}:(a,...m)=>{let o=n(e,a,...m);return s(o)}:R=a=>false;let l=core.createRule({type:"and",validator:R,message:"The value does not match all of the provided validators"}),u=[...r??[]];return l._params=u,typeof l=="function"?l(...u):l}function G(...e){let t=e.some(a=>typeof a=="function"?a.constructor.name==="AsyncFunction":a._async),r=e.map(a=>typeof a=="function"?null:a._params).flat().filter(a=>!!a);function n(a,m,...o){let p=[],b=0;for(let d of a)if(typeof d=="function")p.push(d(m)),b++;else {let M=d._params?.length??0;p.push(d.validator(m,...o.slice(b,M))),M&&(b+=M);}return p}function s(a){return a.some(o=>typeof o!="boolean")?{$valid:a.some(o=>typeof o=="boolean"?!!o:o.$valid),...a.reduce((o,p)=>{if(typeof p=="boolean")return o;let{$valid:b,...d}=p;return {...o,...d}},{})}:a.some(o=>!!o)}let l=core.createRule({type:"or",validator:t?async(a,...m)=>{let o=await Promise.all(n(e,a,...m));return s(o)}:(a,...m)=>{let o=n(e,a,...m);return s(o)},message:"The value does not match any of the provided validators"}),u=[...r??[]];return l._params=u,typeof l=="function"?l(...u):l}function B(e,t){let r,n,s,R,l;typeof e=="function"?(n=e,l=e.constructor.name==="AsyncFunction"):({_type:r,validator:n,_params:R}=e,l=e._async),l?s=async(m,...o)=>i(m)?!await n(m,...o):true:s=(m,...o)=>i(m)?!n(m,...o):true;let u=core.createRule({type:"not",validator:s,message:t??"Error"}),a=[...R??[]];return u._params=a,typeof u=="function"?u(...a):u}var Jt=core.createRule({type:"required",validator:e=>i(e),message:"This field is required"});var Yt=core.createRule({type:"maxLength",validator:(e,t,r)=>{let{allowEqual:n=true}=r??{};return i(e,false)&&i(t)?y(t)?n?D(e)<=t:D(e)<t:(console.warn(`[maxLength] Value or parameter isn't a number, got value: ${e}, parameter: ${t}`),false):true},message:({$value:e,$params:[t]})=>Array.isArray(e)?`This list should have maximum ${t} items`:`The maximum length allowed is ${t}`});var rr=core.createRule({type:"required",validator(e,t){return t?i(e):true},message:"This field is required",active({$params:[e]}){return e}});var X=/^[a-zA-Z]*$/,or=core.createRule({type:"alpha",validator(e){return f(e)?true:g(e,X)},message:"The value is not alphabetical"});var j=/^[a-zA-Z0-9]*$/,mr=core.createRule({type:"alpha",validator(e){return f(e)?true:g(e,j)},message:"The value must be alpha-numeric"});var yr=core.createRule({type:"between",validator:(e,t,r,n)=>{let{allowEqual:s=true}=n??{};if(i(e)&&i(t)&&i(r)){let R=c(e),l=c(t),u=c(r);return y(R)&&y(l)&&y(u)?s?R>=l&&R<=u:R>l&&R<u:(console.warn(`[between] Value or parameters aren't numbers, got value: ${e}, min: ${t}, max: ${r}`),false)}return true},message:({$params:[e,t]})=>`The value must be between ${e} and ${t}`});var re=/^[-]?\d*(\.\d+)?$/,Tr=core.createRule({type:"decimal",validator(e){return f(e)?true:g(e,re)},message:"Value must be decimal"});var ae=/^(?:[A-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]{2,}(?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i,Mr=core.createRule({type:"email",validator(e){return f(e)?true:g(e,ae)},message:"Value must be an valid email address"});var oe=/(^[0-9]*$)|(^-[0-9]+$)/,Vr=core.createRule({type:"integer",validator(e){return f(e)?true:g(e,oe)},message:"Value must be an integer"});var vr=core.createRule({type:"maxValue",validator:(e,t,r)=>{let{allowEqual:n=true}=r??{};return i(e)&&i(t)?y(t)&&!isNaN(c(e))?n?c(e)<=t:c(e)<t:(console.warn(`[maxValue] Value or parameter isn't a number, got value: ${e}, parameter: ${t}`),true):true},message:({$params:[e,t]})=>{let{allowEqual:r=true}=t??{};return r?`Value must be less than or equal to ${e}`:`Value must be less than ${e}`}});var Nr=core.createRule({type:"minLength",validator:(e,t,r)=>{let{allowEqual:n=true}=r??{};return i(e,false)&&i(t)?y(t)?n?D(e)>=t:D(e)>t:(console.warn(`[minLength] Parameter isn't a number, got parameter: ${t}`),false):true},message:({$value:e,$params:[t]})=>Array.isArray(e)?`This list should have at least ${t} items`:`This field should be at least ${t} characters long`});var Or=core.createRule({type:"minValue",validator:(e,t,r)=>{let{allowEqual:n=true}=r??{};return i(e)&&i(t)?y(t)&&!isNaN(c(e))?n?c(e)>=t:c(e)>t:(console.warn(`[minValue] Value or parameter isn't a number, got value: ${e}, parameter: ${t}`),true):true},message:({$params:[e,t]})=>{let{allowEqual:r=true}=t??{};return r?`Value must be greater than or equal to ${e}`:`Value must be greater than ${e}`}});var qr=core.createRule({type:"exactValue",validator:(e,t)=>i(e)&&i(t)?y(t)&&!isNaN(c(e))?c(e)===t:(console.warn(`[exactValue] Value or parameter isn't a number, got value: ${e}, parameter: ${t}`),true):true,message:({$params:[e]})=>`The value must be equal to ${e}`});var Br=core.createRule({type:"exactLength",validator:(e,t)=>i(e,false)&&i(t)?y(t)?D(e)===t:(console.warn(`[minLength] Parameter isn't a number, got parameter: ${t}`),false):true,message:({$params:[e]})=>`This field should be exactly ${e} characters long`});var pe=/^\d*(\.\d+)?$/,Qr=core.createRule({type:"numeric",validator(e){return f(e)?true:g(e,pe)},message:"This field must be numeric"});var en=core.createRule({type:"required",validator(e,t){return t?true:i(e)},message:"This field is required",active({$params:[e]}){return !e}});var an=core.createRule({type:"sameAs",validator(e,t,r="other"){return f(e)?true:e===t},message({$params:[e,t]}){return `Value must be equal to the ${t} value`}});var de=/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i,un=core.createRule({type:"url",validator(e){return f(e)?true:g(e,de)},message:"The value is not a valid URL address"});function Te(){return navigator.languages!=null?navigator.languages[0]:navigator.language}function w(e){return e?new Intl.DateTimeFormat(Te(),{dateStyle:"short"}).format(new Date(e)):"?"}var gn=core.createRule({type:"dateAfter",validator:(e,t)=>i(e)&&i(t)?x(e)&&x(t)?T(e).getTime()>T(t).getTime()?true:{$valid:false,error:"date-not-after"}:{$valid:false,error:"value-or-paramater-not-a-date"}:true,message:({$params:[e],error:t})=>t==="value-or-paramater-not-a-date"?"The inputs must be Dates":`The date must be after ${w(e)}`});var bn=core.createRule({type:"dateBefore",validator:(e,t)=>i(e)&&i(t)?x(e)&&x(t)?T(e).getTime()<T(t).getTime()?true:{$valid:false,error:"date-not-before"}:{$valid:false,error:"value-or-paramater-not-a-date"}:true,message:({$params:[e],error:t})=>t==="value-or-paramater-not-a-date"?"The fields must be Dates":`The date must be before ${w(e)}`});var wn=core.createRule({type:"dateBetween",validator:(e,t,r)=>x(e)&&x(t)&&x(r)?T(e).getTime()>T(t).getTime()&&T(e).getTime()<T(r).getTime():true,message:({$params:[e,t]})=>`The date must be between ${w(e)} and ${w(t)}`});function he(e){if(e.length>3||e.length===0||e[0]==="0"&&e!=="0"||!e.match(/^\d+$/))return false;let t=+e|0;return t>=0&&t<=255}var Wn=core.createRule({type:"ipAddress",validator(e){if(f(e))return true;if(typeof e!="string")return false;let t=e.split(".");return t.length===4&&t.every(he)},message:"The value is not a valid IP address"});var _n=core.createRule({type:"macAddress",validator(e,t=":"){if(f(e))return true;if(typeof e!="string")return false;let r=typeof t=="string"&&t!==""?e.split(t):e.length===12||e.length===16?e.match(/.{2}/g):null;return r!==null&&(r.length===6||r.length===8)&&r.every(we)},message:"The value is not a valid MAC Address"}),we=e=>e.toLowerCase().match(/^[0-9a-f]{2}$/);var kn=core.createRule({type:"checked",validator:e=>i(e)?e===true:true,message:"This field must be checked"});var Sn=core.createRule({type:"contains",validator(e,t){return i(e)&&i(t)?e.includes(t):true},message({$params:[e]}){return `Field must contain ${e}`}});var Kn=core.createRule({type:"startsWith",validator(e,t){return i(e)&&i(t)?e.startsWith(t):true},message({$params:[e]}){return `Field must end with ${e}`}});var Hn=core.createRule({type:"endsWith",validator(e,t){return i(e)&&i(t)?e.endsWith(t):true},message({$params:[e]}){return `Field must end with ${e}`}});var jn=core.createRule({type:"regex",validator(e,t){if(i(e)){let r=Array.isArray(t)?t:[t];return g(e,...r)}return true},message:"This field does not match the required pattern"});function na(e){let t=vue.computed(()=>vue.toValue(e));return h(P((n,s)=>i(n)&&i(s,false)?s.includes(n):true,[t]),({$params:[n]})=>`Value should be one of those options: ${n.join(", ")}.`)}function Ee(e){let t=Object.keys(e).filter(n=>typeof e[e[n]]!="number"),r={};for(let n of t)r[n]=e[n];return Object.values(r)}function sa(e){let t=vue.computed(()=>vue.toValue(e));return h(P((n,s)=>i(n)&&!f(s)?Ee(s).includes(n):true,[t]),({$params:[n]})=>`Value should be one of those options: ${Object.values(n).join(", ")}.`)}function Ra(e){let t=vue.computed(()=>vue.toValue(e));return h(P((n,s)=>s===n,[t]),({$params:[n]})=>`Value should be ${n}.`)}exports.alpha=or;exports.alphaNum=mr;exports.and=q;exports.applyIf=L;exports.between=yr;exports.checked=kn;exports.contains=Sn;exports.dateAfter=gn;exports.dateBefore=bn;exports.dateBetween=wn;exports.decimal=Tr;exports.email=Mr;exports.endsWith=Hn;exports.exactLength=Br;exports.exactValue=qr;exports.getSize=D;exports.integer=Vr;exports.ipAddress=Wn;exports.isDate=x;exports.isEmpty=f;exports.isFilled=i;exports.isNumber=y;exports.literal=Ra;exports.macAddress=_n;exports.matchRegex=g;exports.maxLength=Yt;exports.maxValue=vr;exports.minLength=Nr;exports.minValue=Or;exports.nativeEnum=sa;exports.not=B;exports.numeric=Qr;exports.oneOf=na;exports.or=G;exports.regex=jn;exports.required=Jt;exports.requiredIf=rr;exports.requiredUnless=en;exports.sameAs=an;exports.startsWith=Kn;exports.toDate=T;exports.toNumber=c;exports.url=un;exports.withAsync=E;exports.withMessage=h;exports.withParams=P;exports.withTooltip=_;
package/index.cjs DELETED
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- if (process.env.NODE_ENV === 'production') {
4
- module.exports = require('./dist/regle-rules.min.cjs');
5
- } else {
6
- module.exports = require('./dist/regle-rules.cjs');
7
- }
package/index.js DELETED
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- if (process.env.NODE_ENV === 'production') {
4
- module.exports = require('./dist/regle-rules.min.cjs');
5
- } else {
6
- module.exports = require('./dist/regle-rules.cjs');
7
- }