@apia/validations 0.0.7
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.
- package/LICENSE.md +21 -0
- package/README.md +28 -0
- package/dist/index.d.ts +643 -0
- package/dist/index.js +10617 -0
- package/dist/index.js.map +1 -0
- package/lang/bg.ts +27 -0
- package/lang/da.ts +31 -0
- package/lang/de.ts +26 -0
- package/lang/en.ts +34 -0
- package/lang/es.ts +38 -0
- package/lang/fa.ts +39 -0
- package/lang/fr.ts +36 -0
- package/lang/gr.ts +24 -0
- package/lang/hr.ts +31 -0
- package/lang/hu.ts +30 -0
- package/lang/it.ts +25 -0
- package/lang/ja.ts +25 -0
- package/lang/jp.ts +25 -0
- package/lang/nl.ts +26 -0
- package/lang/pl.ts +35 -0
- package/lang/pt.ts +27 -0
- package/lang/ro.ts +37 -0
- package/lang/ru.ts +26 -0
- package/package.json +39 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [year] [fullname]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Initiator
|
|
2
|
+
|
|
3
|
+
Este package se creó con la única utilidad de copiarlo entero y pegarlo a la hora de crear un nuevo package.
|
|
4
|
+
|
|
5
|
+
Este iniciador permite crear un paquete que compila typescript y puede ser importado desde otros packages.
|
|
6
|
+
|
|
7
|
+
## IMPORTANTE
|
|
8
|
+
|
|
9
|
+
Los archivos **tsconfig.json** y **tsup.config.ts** no son archivos únicos sino symlinks a archivos de configuración comunes a todos los packages. En caso de que sea necesario modificar alguno de ellos **que en la gran mayoría de los casos no sería necesario**, es necesario eliminar el archivo a modificar y crear uno nuevo.
|
|
10
|
+
|
|
11
|
+
## Procedimiento
|
|
12
|
+
|
|
13
|
+
- Copiar la carpeta initiator y pegarla con otro nombre dentro de packages.
|
|
14
|
+
- Modificar el package.json:
|
|
15
|
+
- Eliminar la línea ```private: true```.
|
|
16
|
+
- Cambiar la ocurrencia `initiator` por el nombre del nuevo paquete.
|
|
17
|
+
- Agregar los scripts convenientes: dev, build, etc.
|
|
18
|
+
- Ejecutar el comando lerna bootstrap desde la carpeta raíz.
|
|
19
|
+
|
|
20
|
+
Luego de ejecutar estos pasos, el package estaría listo para comenzar a usarse.
|
|
21
|
+
|
|
22
|
+
Este package trae como dependencias por defecto theme-ui y react. Si se desea agregar más dependencias se debe ejecutar el comando ```lerna add --scope="@apia/packageName" dependencyName```. Ejemplo, si creamos un paquete con el nombre @apia/myPackage y queremos agregar lodash-es como dependencia, ejecutamos el comando ```lerna add --scope="@apia/myPackage" lodash-es```.
|
|
23
|
+
|
|
24
|
+
**Importante 1**: Dado que estamos desarrollando packages, es importante determinar si las dependencias que vamos a agregar son de tipo dependency o de tipo peerDependency.
|
|
25
|
+
|
|
26
|
+
**Importante 2**: lerna no permite instalar de a varias dependencias a la vez como lo hace npm, por lo tanto, si se desea agregar varias dependencias se debe ejecutar el comando anterior tantas veces como dependencias se quiera agregar.
|
|
27
|
+
|
|
28
|
+
**Importante 3**: React y theme-ui vienen instalados como peerDependencies. En caso de no ser necesarios pueden ser removidos, pero en cualquier caso asegurarse de que estas dependencias no sean instaladas como dependencies puesto que esto causaría comportamientos indeseados en la aplicación.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
import * as theme_ui_jsx_runtime from 'theme-ui/jsx-runtime';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
import { TModify, TId } from '@apia/util';
|
|
4
|
+
import { BoxProps, ButtonProps, InputProps, LabelProps, RadioProps, SelectProps, SwitchProps, TextareaProps } from 'theme-ui';
|
|
5
|
+
import { TNumberInput } from '@apia/components';
|
|
6
|
+
|
|
7
|
+
declare const formcheckLanguage: {
|
|
8
|
+
required: string;
|
|
9
|
+
alpha: string;
|
|
10
|
+
alphanum: string;
|
|
11
|
+
nodigit: string;
|
|
12
|
+
digit: string;
|
|
13
|
+
digitmin: string;
|
|
14
|
+
digitltd: string;
|
|
15
|
+
number: string;
|
|
16
|
+
email: string;
|
|
17
|
+
image: string;
|
|
18
|
+
phone: string;
|
|
19
|
+
url: string;
|
|
20
|
+
confirm: string;
|
|
21
|
+
differs: string;
|
|
22
|
+
length_str: string;
|
|
23
|
+
length_fix: string;
|
|
24
|
+
lengthmax: string;
|
|
25
|
+
lengthmin: string;
|
|
26
|
+
words_min: string;
|
|
27
|
+
words_max: string;
|
|
28
|
+
words_range: string;
|
|
29
|
+
checkbox: string;
|
|
30
|
+
checkboxes_group: string;
|
|
31
|
+
radios: string;
|
|
32
|
+
select: string;
|
|
33
|
+
select_multiple: string;
|
|
34
|
+
errorsTitle: string;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
declare global {
|
|
38
|
+
interface Window {
|
|
39
|
+
[key: string]: string;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
type TValidate = Partial<TModify<Record<keyof typeof formcheckLanguage, boolean>, {
|
|
43
|
+
digitmin: number;
|
|
44
|
+
digitltd: [number, number];
|
|
45
|
+
confirm: string;
|
|
46
|
+
differs: string;
|
|
47
|
+
length_str: [number, number];
|
|
48
|
+
length_fix: number;
|
|
49
|
+
words_min: number;
|
|
50
|
+
words_max: number;
|
|
51
|
+
words_range: [number, number];
|
|
52
|
+
checkboxes_group: number;
|
|
53
|
+
}> & {
|
|
54
|
+
patternMessage: string;
|
|
55
|
+
pattern: RegExp | string;
|
|
56
|
+
digitmax: number;
|
|
57
|
+
validName?: string;
|
|
58
|
+
maxLength: number;
|
|
59
|
+
minLength: number;
|
|
60
|
+
min: number;
|
|
61
|
+
max: number;
|
|
62
|
+
}>;
|
|
63
|
+
interface IFieldDefinition<ValueType = string> {
|
|
64
|
+
toolTip: string;
|
|
65
|
+
label: string;
|
|
66
|
+
name: string;
|
|
67
|
+
validate?: TValidate;
|
|
68
|
+
value: ValueType;
|
|
69
|
+
options?: {
|
|
70
|
+
label: string;
|
|
71
|
+
value: number | number;
|
|
72
|
+
selected?: boolean;
|
|
73
|
+
}[];
|
|
74
|
+
}
|
|
75
|
+
type TPromiseOrNot<Type> = Promise<Type> | Type;
|
|
76
|
+
type TSuccessfulValidation<ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType> = {
|
|
77
|
+
values: ValueType;
|
|
78
|
+
submitValues: SubmitValueType;
|
|
79
|
+
};
|
|
80
|
+
type TWrongValidation = {
|
|
81
|
+
errors: Record<string, string>;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Esta interfaz representa el resultado de la validación
|
|
85
|
+
* de un formulario.
|
|
86
|
+
*/
|
|
87
|
+
type TValidationResult<ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType> = TSuccessfulValidation<ValueType, SubmitValueType> | TWrongValidation;
|
|
88
|
+
type TFieldValidationResult = true | string;
|
|
89
|
+
type TValidationFunction<ValueType> = (value: ValueType, formName: string) => TPromiseOrNot<TFieldValidationResult>;
|
|
90
|
+
type TValidationSubmitValueParser<ValueType = unknown, SubmitValueType = ValueType> = (value: ValueType) => SubmitValueType;
|
|
91
|
+
type TValidationValueParser<ValueType = unknown, ValidationValueType = unknown> = (value: ValueType) => ValidationValueType;
|
|
92
|
+
/**
|
|
93
|
+
* Esta interfaz representa el estado de un campo dentro
|
|
94
|
+
* del hook de validación.
|
|
95
|
+
*
|
|
96
|
+
* Las funcionalidades contempladas hasta el momento son:
|
|
97
|
+
*
|
|
98
|
+
* - Contener los valores del formulario.
|
|
99
|
+
* - Foco: Se hará querySelector sobre el form que lo contiene
|
|
100
|
+
* con el nombre provisto.
|
|
101
|
+
* - Función de validación o lista de reglas.
|
|
102
|
+
* - Manejo de errores.
|
|
103
|
+
* - Parsearlos para hacer submit.
|
|
104
|
+
*/
|
|
105
|
+
type TValidationField<ValueType = any, SubmitValueType = ValueType> = {
|
|
106
|
+
error?: string | null;
|
|
107
|
+
isTouched: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* El nombre se utilizará para hacer foco en el campo en caso
|
|
110
|
+
* de que la validación del mismo fallara. Para ello se
|
|
111
|
+
* intenta recuperar un campo con el selector
|
|
112
|
+
* [name=${name}, #${name}], en caso de que el selector no
|
|
113
|
+
* encontrar ningún campo, se intentará hacer foco en el
|
|
114
|
+
* siguiente campo con error.
|
|
115
|
+
*/
|
|
116
|
+
name: string;
|
|
117
|
+
/**
|
|
118
|
+
* Como dice el nombre, es posible cambiar el nombre de un
|
|
119
|
+
* campo al hacer submit.
|
|
120
|
+
*/
|
|
121
|
+
submitName?: string;
|
|
122
|
+
/**
|
|
123
|
+
* Es posible recibir un valor ya parseado en el callback
|
|
124
|
+
* onValidate del Form, para ello se puede proveer este
|
|
125
|
+
* callback, que será llamado previo a llamar a onValidate.
|
|
126
|
+
*/
|
|
127
|
+
submitValueParser?: TValidationSubmitValueParser<ValueType, SubmitValueType | undefined>;
|
|
128
|
+
/**
|
|
129
|
+
* Es posible pasar una función de validación personalizada
|
|
130
|
+
* para casos en los que la validación es significativamente
|
|
131
|
+
* compleja. En la mayoría de los casos debería bastar con
|
|
132
|
+
* la propiedad validationRules.
|
|
133
|
+
*/
|
|
134
|
+
validationFunction?: TValidationFunction<ValueType>;
|
|
135
|
+
/**
|
|
136
|
+
* Permite pasar una serie de reglas que el campo debe cumplir
|
|
137
|
+
* al validar.
|
|
138
|
+
*/
|
|
139
|
+
validationRules?: IFieldDefinition['validate'];
|
|
140
|
+
validationValueParser?: TValidationValueParser<ValueType>;
|
|
141
|
+
value: ValueType;
|
|
142
|
+
};
|
|
143
|
+
type TRegisterFormOptions = Partial<{
|
|
144
|
+
/**
|
|
145
|
+
* Si esta propiedad está seteada en true, el formulario se registrará y
|
|
146
|
+
* aquellos campos que ya tuvieran valor en el store no se volverán a
|
|
147
|
+
* registrar. En caso de que se incluyera initialValue, se hará updateValue de
|
|
148
|
+
* estos campos.
|
|
149
|
+
*/
|
|
150
|
+
avoidFieldsOverride: boolean;
|
|
151
|
+
initialValues: Record<string, unknown>;
|
|
152
|
+
}>;
|
|
153
|
+
type TRegisterFieldOptions = {
|
|
154
|
+
avoidPropagation?: boolean;
|
|
155
|
+
registerIfExists?: boolean;
|
|
156
|
+
};
|
|
157
|
+
type TRegisterField = Partial<TValidationField> & Pick<TValidationField, 'name'>;
|
|
158
|
+
type TFormState = {
|
|
159
|
+
fields: string[];
|
|
160
|
+
name: string;
|
|
161
|
+
isTouched: boolean;
|
|
162
|
+
isValid: boolean;
|
|
163
|
+
validationResult: TValidationResult<Record<string, unknown>> | null;
|
|
164
|
+
} & Pick<TRegisterFormOptions, 'avoidFieldsOverride'>;
|
|
165
|
+
|
|
166
|
+
type TOnValidate<ValueType extends Record<string, unknown> = Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType> = (validationResult: TValidationResult<ValueType, SubmitValueType>) => unknown;
|
|
167
|
+
interface IForm<ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType> {
|
|
168
|
+
/**
|
|
169
|
+
* Si se pasa en true, los campos que se registren en este form no
|
|
170
|
+
* sobreescribirán valores previos si es que existen, sin importar el valor de
|
|
171
|
+
* avoidRegisterIfExists pasado al useField.
|
|
172
|
+
*/
|
|
173
|
+
avoidFieldsOverride?: boolean;
|
|
174
|
+
/**
|
|
175
|
+
* Impide que se apliquen los estilos que indican que un campo fue alterado.
|
|
176
|
+
*/
|
|
177
|
+
avoidFieldsTouch?: boolean;
|
|
178
|
+
children: React.ReactNode;
|
|
179
|
+
className?: string;
|
|
180
|
+
initialValues?: Partial<ValueType>;
|
|
181
|
+
name?: string;
|
|
182
|
+
onUnmount?: () => unknown;
|
|
183
|
+
/**
|
|
184
|
+
* Cuando se ejecuta una acción de validación desde
|
|
185
|
+
* algún lugar de la aplicación se llama a este método
|
|
186
|
+
* con el resultado de dicha ejecución.
|
|
187
|
+
*/
|
|
188
|
+
onValidate?: TOnValidate<ValueType, SubmitValueType>;
|
|
189
|
+
/**
|
|
190
|
+
* Permite definir si el formulario va a ser borrado de la validación al ser
|
|
191
|
+
* desmontado
|
|
192
|
+
*/
|
|
193
|
+
unregisterOnUnmount?: boolean;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Cuando se desea usar el sistema de validación,
|
|
197
|
+
* se debe utilizar este componente como form contenedor
|
|
198
|
+
* de todos los campos que quieran validarse.
|
|
199
|
+
*
|
|
200
|
+
* Es importante que no se coloquen formularios dentro
|
|
201
|
+
* de formularios ya que esto podría afectar negativamente
|
|
202
|
+
* el proceso de validación.
|
|
203
|
+
*
|
|
204
|
+
* @props
|
|
205
|
+
* *name:* Se puede pasar un nombre para identificar
|
|
206
|
+
* el form. Este nombre será utilizado para almacenar
|
|
207
|
+
* la información en Redux, por lo que si se desea
|
|
208
|
+
* acceder a la información recolectada por la librería,
|
|
209
|
+
* es conveniente pasar un nombre conocido y único. En
|
|
210
|
+
* caso de no se pase ningún nombre, la aplicación
|
|
211
|
+
* generará un nombre único automaticamente.
|
|
212
|
+
*
|
|
213
|
+
* *onValidate:* Un callback que será llamado cuando
|
|
214
|
+
* se invoque el método validateForm del store o cuando
|
|
215
|
+
* se lance el evento de submit del elemento form (por
|
|
216
|
+
* ejemplo mediante un click en un botón que no tenga
|
|
217
|
+
* type="button"), con el resultado de la validación.
|
|
218
|
+
*
|
|
219
|
+
* @see useField
|
|
220
|
+
* @see useForm
|
|
221
|
+
*
|
|
222
|
+
* @important Debido a que este hook renderiza un elemento
|
|
223
|
+
* form en el DOM, es importante agregar el atributo
|
|
224
|
+
* type="button" a todos los botones dentro del formulario
|
|
225
|
+
* que no se desea que disparen la validación.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* Para ver un ejemplo funcional, mira el componente
|
|
229
|
+
* Invitations.tsx
|
|
230
|
+
*
|
|
231
|
+
* // IMPORTANTE: El tipado del componente Form es genérico
|
|
232
|
+
* // por lo que es posible instanciarlo como se muestra a
|
|
233
|
+
* // continuación, lo que nos da el tipado correcto en el
|
|
234
|
+
* // callback onValidate.
|
|
235
|
+
* <Form<FormDataType> onValidate={(res) => {
|
|
236
|
+
* if(hasSucceedValidation(res)) {
|
|
237
|
+
* // Do something with submitValues
|
|
238
|
+
* } else {
|
|
239
|
+
* // Do something with errors
|
|
240
|
+
* }
|
|
241
|
+
* }}>
|
|
242
|
+
* ...{children}
|
|
243
|
+
* </Form>
|
|
244
|
+
*/
|
|
245
|
+
declare const Form: <ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType>({ avoidFieldsOverride, avoidFieldsTouch, children, className, name, initialValues, onUnmount, onValidate, unregisterOnUnmount, }: IForm<ValueType, SubmitValueType>) => theme_ui_jsx_runtime.JSX.Element | null;
|
|
246
|
+
|
|
247
|
+
interface IFormContext<ValueType extends Record<string, unknown> = Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType> {
|
|
248
|
+
avoidFieldsTouch?: boolean;
|
|
249
|
+
name: string;
|
|
250
|
+
validate: () => Promise<TValidationResult<ValueType, SubmitValueType>>;
|
|
251
|
+
}
|
|
252
|
+
declare const FormContext: React.Context<IFormContext<Record<string, unknown>, Record<string, unknown>>>;
|
|
253
|
+
/**
|
|
254
|
+
* Provee acceso de forma sencilla al contexto de
|
|
255
|
+
* validación, que básicamente posee el nombre del
|
|
256
|
+
* form en caso de que se quiera usar para acceder
|
|
257
|
+
* a través de Redux a la información del mismo y un
|
|
258
|
+
* método validate, que dispara la validación del
|
|
259
|
+
* form.
|
|
260
|
+
*
|
|
261
|
+
* En la práctica, el método validate es casi
|
|
262
|
+
* innecesario, ya que la validación se puede disparar
|
|
263
|
+
* con cualquier botón que no tenga seteado el
|
|
264
|
+
* atributo type="button" (esto es así ya que en el
|
|
265
|
+
* DOM se renderiza un elemento de tipo form).
|
|
266
|
+
*/
|
|
267
|
+
declare function useFormContext(): IFormContext<Record<string, unknown>, Record<string, unknown>>;
|
|
268
|
+
|
|
269
|
+
interface IPropsStoreConf {
|
|
270
|
+
logCommands: {
|
|
271
|
+
propsStore?: string;
|
|
272
|
+
updateProp?: string;
|
|
273
|
+
propsSuscriptors?: string;
|
|
274
|
+
propsLog?: string;
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
declare class PropsStore<PropsType extends Record<TId, unknown> = Record<TId, unknown>> {
|
|
278
|
+
private configuration?;
|
|
279
|
+
log: unknown;
|
|
280
|
+
fields: Record<TId, PropsType>;
|
|
281
|
+
suscriptors: Record<TId, TPropsSuscriptor<PropsType>[]>;
|
|
282
|
+
loggers: Record<string, (props: unknown[]) => void>;
|
|
283
|
+
constructor(configuration?: IPropsStoreConf | undefined);
|
|
284
|
+
destructor(): void;
|
|
285
|
+
getAllFields(): Record<TId, PropsType>;
|
|
286
|
+
/**
|
|
287
|
+
* Devuelve los props actuales de un campo.
|
|
288
|
+
*/
|
|
289
|
+
getFieldProps<ParsedPropsType = PropsType>(fieldId: TId): ParsedPropsType;
|
|
290
|
+
removeField(fieldId: TId): void;
|
|
291
|
+
/**
|
|
292
|
+
* Permite establecer un suscriptor que será llamado
|
|
293
|
+
* cada vez que las props del campo especificado cambien.
|
|
294
|
+
*/
|
|
295
|
+
suscribe(fieldId: TId, callback: TPropsSuscriptor<PropsType>): () => void;
|
|
296
|
+
/**
|
|
297
|
+
* Actualiza o crea las props de un campo.
|
|
298
|
+
*
|
|
299
|
+
* La tercera prop está relacionada
|
|
300
|
+
*/
|
|
301
|
+
updateField<NewPropsType extends Record<TId, unknown> = Partial<PropsType>>(fieldId: TId, props: Partial<NewPropsType>, conf?: TUpdateFieldConfiguration): void;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
type TProperties = Record<string, unknown>;
|
|
305
|
+
type TPropsSuscriptor<PropsType extends Record<string, unknown> = TProperties> = (props: PropsType, urgent?: boolean) => unknown;
|
|
306
|
+
type TPropsSelector<Selected = any, PropsType = TProperties> = (props: PropsType) => Selected;
|
|
307
|
+
/**
|
|
308
|
+
* La función comparadora debe devolver true cuando
|
|
309
|
+
* los elementos son iguales o false cuando son
|
|
310
|
+
* distintos.
|
|
311
|
+
*/
|
|
312
|
+
type TPropsComparator<Selected> = (prevProps: Selected | undefined, newProps: Selected | undefined) => boolean;
|
|
313
|
+
type TPropsConfiguration<Selected, PropsType extends Record<string, unknown> = TProperties> = {
|
|
314
|
+
selector?: TPropsSelector<Selected, PropsType>;
|
|
315
|
+
comparator?: TPropsComparator<Selected>;
|
|
316
|
+
initialValue?: Selected;
|
|
317
|
+
propsStore?: PropsStore<PropsType>;
|
|
318
|
+
};
|
|
319
|
+
type TUpdateFieldConfiguration = Partial<{
|
|
320
|
+
noEmit: boolean;
|
|
321
|
+
isUrgent: boolean;
|
|
322
|
+
}>;
|
|
323
|
+
|
|
324
|
+
declare const validationsStore: {
|
|
325
|
+
activeForms: string[];
|
|
326
|
+
timeouts: Record<string, ReturnType<typeof setTimeout> | true>;
|
|
327
|
+
getFieldStore(formName: string, fieldName: string): TValidationField<any, any>;
|
|
328
|
+
getFormStore(formName: string): TFormState;
|
|
329
|
+
updateFieldStore(formName: string, fieldName: string, props: Partial<TValidationField>, noEmit?: boolean): void;
|
|
330
|
+
updateFormStore(formName: string, newState: Partial<TFormState>): void;
|
|
331
|
+
enableFormTouch(formName: string): void;
|
|
332
|
+
existsField: (formName: string, fieldName: string) => boolean;
|
|
333
|
+
makeFieldName(formName: string, fieldName: string): string;
|
|
334
|
+
makeFormName(formName: string): string;
|
|
335
|
+
registerField: (formName: string, registerData: TRegisterField, options?: TRegisterFieldOptions) => void;
|
|
336
|
+
/**
|
|
337
|
+
* Inicializa el estado de un nuevo formulario
|
|
338
|
+
*/
|
|
339
|
+
registerForm: (formName: string, props?: Partial<{
|
|
340
|
+
avoidFieldsOverride: boolean;
|
|
341
|
+
initialValues: Record<string, unknown>;
|
|
342
|
+
}>) => void;
|
|
343
|
+
/**
|
|
344
|
+
* Setea el valor del campo con el nombre provisto. Si el campo no existe
|
|
345
|
+
* en el formulario lo crea.
|
|
346
|
+
*/
|
|
347
|
+
setFieldValue: (formName: string, fieldName: string, newValue: unknown, options?: Partial<{
|
|
348
|
+
avoidPropagation?: boolean | undefined;
|
|
349
|
+
markFormAsTouched: boolean;
|
|
350
|
+
}> | undefined) => void;
|
|
351
|
+
setFormIsTouched: (formName: string, isTouched?: boolean) => void;
|
|
352
|
+
/**
|
|
353
|
+
* Elimina un campo del registro de validación de un formulario. De esta
|
|
354
|
+
* forma cualquier validación que pudiera aplicarse sobre el mismo, ya no se
|
|
355
|
+
* aplicará.
|
|
356
|
+
*/
|
|
357
|
+
unregisterField: (formName: string, fieldName: string) => void;
|
|
358
|
+
/**
|
|
359
|
+
* Elimina un formulario del store de validación junto con todos los campos
|
|
360
|
+
* asociados al mismo.
|
|
361
|
+
*/
|
|
362
|
+
unregisterForm: (formName: string) => void;
|
|
363
|
+
/**
|
|
364
|
+
* Actualiza las propiedades de un campo, si no existe, lo registra en el
|
|
365
|
+
* formulario.
|
|
366
|
+
*/
|
|
367
|
+
updateField: (formName: string, field: Partial<TValidationField> & Pick<TValidationField, 'name'>, options?: Partial<{
|
|
368
|
+
avoidPropagation?: boolean | undefined;
|
|
369
|
+
markFormAsTouched: boolean;
|
|
370
|
+
}> | undefined) => void;
|
|
371
|
+
/**
|
|
372
|
+
* Actualiza múltiples campos al mismo tiempo.
|
|
373
|
+
*/
|
|
374
|
+
updateMultipleFields: (formName: string, fields: (Partial<TValidationField> & Pick<TValidationField, 'name'>)[], options?: Partial<{
|
|
375
|
+
avoidPropagation?: boolean | undefined;
|
|
376
|
+
markFormAsTouched: boolean;
|
|
377
|
+
}> | undefined) => void;
|
|
378
|
+
/**
|
|
379
|
+
* Ejecuta la validación sobre un formulario. En caso de que la validación
|
|
380
|
+
* falle, se intenta hacer foco sobre el campo que no pudo validar.
|
|
381
|
+
* Es importante notar que en caso de que un campo requiera validación,
|
|
382
|
+
* debería estar presente en el DOM.
|
|
383
|
+
*
|
|
384
|
+
* No es necesario que el campo esté visible, ya que en caso de estar oculto
|
|
385
|
+
* (por ejemplo por ser hijo de un acordeón), se emitirá un evento para
|
|
386
|
+
* expandir al elemento padre que lo estuviera ocultando.
|
|
387
|
+
*
|
|
388
|
+
* @returns Devuelve una promesa que al ser resuelta otorga un objeto de tipo
|
|
389
|
+
* TValidationResult. Este tipo está pensado para ser usado en conjunto con
|
|
390
|
+
* el método hasSucceedFormValidation, que determinará si la validación fue
|
|
391
|
+
* exitosa o hubo errores.
|
|
392
|
+
*
|
|
393
|
+
* @example
|
|
394
|
+
*
|
|
395
|
+
* const result = await validationStore.validateForm('myForm');
|
|
396
|
+
* if(hasSucceedValidation(result)) {
|
|
397
|
+
* console.log('Success!', result);
|
|
398
|
+
* } else {
|
|
399
|
+
* console.error('Validation error', result);
|
|
400
|
+
* }
|
|
401
|
+
*/
|
|
402
|
+
validateForm: <ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType>(formName: string) => Promise<TValidationResult<ValueType, SubmitValueType>>;
|
|
403
|
+
};
|
|
404
|
+
/**
|
|
405
|
+
* Este hook permite suscribirse a los cambios realizados en el
|
|
406
|
+
* store de validación de un formulario. Funciona igual a un
|
|
407
|
+
* useAppSelector en cuanto a la función selectora y comparadora.
|
|
408
|
+
*
|
|
409
|
+
* @param selector
|
|
410
|
+
* @param comparator
|
|
411
|
+
* @returns
|
|
412
|
+
*/
|
|
413
|
+
declare function useFormSelector<Selected = any>(formName: string, selector: TPropsSelector<Selected, TFormState>, comparator?: TPropsComparator<Selected>): Selected;
|
|
414
|
+
/**
|
|
415
|
+
* Este hook permite suscribirse a los cambios realizados en el
|
|
416
|
+
* store de validación de un campo de formulario. Funciona igual a un
|
|
417
|
+
* useAppSelector en cuanto a la función selectora y comparadora.
|
|
418
|
+
*
|
|
419
|
+
* @param selector
|
|
420
|
+
* @param comparator
|
|
421
|
+
* @returns
|
|
422
|
+
*/
|
|
423
|
+
declare function useFieldSelector<ValueType = unknown, SubmitValueType = unknown, Selected = any>(formName: string, fieldName: string, selector?: TPropsSelector<Selected, TValidationField<ValueType, SubmitValueType>>, comparator?: TPropsComparator<Selected>): Selected;
|
|
424
|
+
declare function useFieldSelector<ValueType = unknown, SubmitValueType = unknown, Selected = any>(formName: string, fieldName: string, configurator?: TPropsConfiguration<Selected, TValidationField<ValueType, SubmitValueType>>): Selected;
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Determina si la validación de un campo resultó exitosa.
|
|
428
|
+
*/
|
|
429
|
+
declare function hasSucceedFieldValidation(result: TFieldValidationResult): result is true;
|
|
430
|
+
/**
|
|
431
|
+
* Determina si la validación de un formulario resultó
|
|
432
|
+
* exitosa. Está pensada para utilizar en el callback
|
|
433
|
+
* onValidate de Form o en la acción validationsActions.validateForm
|
|
434
|
+
*/
|
|
435
|
+
declare function hasSucceedFormValidation<ValueType extends Record<string, unknown>, SubmitValueType extends Record<keyof ValueType, unknown> = ValueType>(result: TValidationResult<ValueType, SubmitValueType>): result is TSuccessfulValidation<ValueType, SubmitValueType>;
|
|
436
|
+
declare function classToValidationFunction<T = string>(className: string): TValidationField<T>['validationFunction'];
|
|
437
|
+
declare function classToValidate(className: string): IFieldDefinition['validate'];
|
|
438
|
+
/**
|
|
439
|
+
* Realiza la carga de los mensajes de errores para el lenguaje
|
|
440
|
+
* especificado. Este método debe llamarse antes de utilizar
|
|
441
|
+
* las validaciones.
|
|
442
|
+
*/
|
|
443
|
+
declare function initValidations(): Promise<void>;
|
|
444
|
+
|
|
445
|
+
type TUseField<ValueType = unknown, SubmitValueType = ValueType> = Omit<TValidationField<ValueType, SubmitValueType>, 'error' | 'value' | 'isTouched'> & {
|
|
446
|
+
/**
|
|
447
|
+
* Con esta propiedad es posible evitar que el campo
|
|
448
|
+
* se registre cuando ya fue registrado previamente en
|
|
449
|
+
* el store. De esta forma, se evitaría escribir sobre
|
|
450
|
+
* un valor que ya estaba seteado anteriormente.
|
|
451
|
+
*/
|
|
452
|
+
avoidRegisterIfExists?: boolean;
|
|
453
|
+
/**
|
|
454
|
+
* Si se está fuera de contexto de validación, se puede pasar un formName
|
|
455
|
+
* para evitar que el hook lo intente tomar de contexto.
|
|
456
|
+
*/
|
|
457
|
+
formName?: string;
|
|
458
|
+
initialValue?: ValueType;
|
|
459
|
+
removeOnUnmount?: boolean;
|
|
460
|
+
};
|
|
461
|
+
/**
|
|
462
|
+
* Este hook permite registrar un field para ser validado,
|
|
463
|
+
* o simplemente para recolectar su valor, e incluso aplicar
|
|
464
|
+
* una función de transformación de dicho valor antes de
|
|
465
|
+
* hacer submit.
|
|
466
|
+
*
|
|
467
|
+
* @returns
|
|
468
|
+
* *error:* Es null mientras que no haya errores de
|
|
469
|
+
* validación, y un string en caso de que si lo haya.
|
|
470
|
+
*
|
|
471
|
+
* *value:* Es el valor actual del campo.
|
|
472
|
+
*
|
|
473
|
+
* *name:* Debería utilizarse para dar * valor al atributo
|
|
474
|
+
* name o id del contenedor que debe recibir el foco en caso
|
|
475
|
+
* de que la validación fallara. (Esto es, cuando se deba
|
|
476
|
+
* realizar foco porque la validación falló, la librería
|
|
477
|
+
* intentará encontrar un campo con el selector
|
|
478
|
+
* [name=${name}, #${name}] dentro del formulario).
|
|
479
|
+
*
|
|
480
|
+
* *onChange:* Se utiliza para setear el valor del campo,
|
|
481
|
+
* puede utilizarse directamente como callback para la
|
|
482
|
+
* propiedad onChange que aceptan la mayoría de los campos,
|
|
483
|
+
* ya que intentará setear el valor con ev.target.value
|
|
484
|
+
* y si esa propiedad no está definida, lo hará directamente
|
|
485
|
+
* con ev.
|
|
486
|
+
*
|
|
487
|
+
* @example
|
|
488
|
+
* // Si se desea un ejemplo más complejo, vea el componente
|
|
489
|
+
* // Invitations.tsx que se encuentra dentro del directorio
|
|
490
|
+
* // de la librería.
|
|
491
|
+
*
|
|
492
|
+
* const inputProps = useField<string>({
|
|
493
|
+
name: 'name',
|
|
494
|
+
validationRules: {
|
|
495
|
+
required: true,
|
|
496
|
+
minLength: 5,
|
|
497
|
+
maxLength: 10
|
|
498
|
+
},
|
|
499
|
+
initialValue: metadata.value,
|
|
500
|
+
* });
|
|
501
|
+
|
|
502
|
+
return <Box>
|
|
503
|
+
<Input {...inputProps} />
|
|
504
|
+
<ValidationError name="name" />
|
|
505
|
+
</Box>
|
|
506
|
+
*/
|
|
507
|
+
declare function useField<ValueType = unknown, SubmitValueType = ValueType>(fieldDefinition: TUseField<ValueType, SubmitValueType>): {
|
|
508
|
+
error: string | null | undefined;
|
|
509
|
+
isTouched: boolean;
|
|
510
|
+
name: string;
|
|
511
|
+
onChange: (ev: React.ChangeEvent | ValueType) => void;
|
|
512
|
+
updateValidations: ({ validationFunction, validationRules, }: Pick<TValidationField, 'validationRules' | 'validationFunction'>) => void;
|
|
513
|
+
value: ValueType;
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
interface IWrapper extends BoxProps {
|
|
517
|
+
name: string;
|
|
518
|
+
label?: string;
|
|
519
|
+
children: React.ReactNode;
|
|
520
|
+
required?: boolean;
|
|
521
|
+
avoidSemicolon?: boolean;
|
|
522
|
+
}
|
|
523
|
+
declare const FieldWrapper: ({ name, label, avoidSemicolon, children, className, as, ...props }: IWrapper) => theme_ui_jsx_runtime.JSX.Element;
|
|
524
|
+
|
|
525
|
+
type TDefaultFieldType<ValueType = string> = Omit<TUseField<ValueType>, 'error' | 'value' | 'isTouched'> & {
|
|
526
|
+
label?: string;
|
|
527
|
+
initialValue?: ValueType;
|
|
528
|
+
validationClass?: string;
|
|
529
|
+
} & Pick<IWrapper, 'avoidSemicolon'>;
|
|
530
|
+
|
|
531
|
+
type TCheckbox = Omit<ButtonProps, 'onChange'> & Pick<InputProps, 'onChange'> & TDefaultFieldType & {
|
|
532
|
+
native?: boolean;
|
|
533
|
+
};
|
|
534
|
+
declare const Checkbox: React.ForwardRefExoticComponent<Omit<TCheckbox, "ref"> & React.RefAttributes<HTMLButtonElement>>;
|
|
535
|
+
|
|
536
|
+
type TDeletableInput = InputProps & TDefaultFieldType;
|
|
537
|
+
declare const DeletableInput: React.ForwardRefExoticComponent<Omit<TDeletableInput, "ref"> & React.RefAttributes<HTMLInputElement>>;
|
|
538
|
+
|
|
539
|
+
type TFieldLabel = LabelProps & {
|
|
540
|
+
avoidSemicolon?: boolean;
|
|
541
|
+
children?: React.ReactNode;
|
|
542
|
+
required?: boolean;
|
|
543
|
+
};
|
|
544
|
+
declare const FieldLabel: ({ avoidSemicolon, children, required, ...props }: TFieldLabel) => theme_ui_jsx_runtime.JSX.Element;
|
|
545
|
+
|
|
546
|
+
type TFileInput = Omit<InputProps, 'onChange' | 'type' | 'value' | 'multiple'> & TDefaultFieldType<File | null> & Pick<TUseField, 'removeOnUnmount'> & Pick<IWrapper, 'avoidSemicolon'>;
|
|
547
|
+
declare const FileInput: React.MemoExoticComponent<React.ForwardRefExoticComponent<Omit<TFileInput, "ref"> & React.RefAttributes<HTMLInputElement>>>;
|
|
548
|
+
|
|
549
|
+
type TInput$1 = InputProps & TDefaultFieldType;
|
|
550
|
+
declare const Input: React.MemoExoticComponent<React.ForwardRefExoticComponent<Omit<TInput$1, "ref"> & React.RefAttributes<HTMLInputElement>>>;
|
|
551
|
+
|
|
552
|
+
type TInput = TNumberInput & TDefaultFieldType;
|
|
553
|
+
declare const NumberInputf: React.MemoExoticComponent<React.ForwardRefExoticComponent<Omit<TInput, "ref"> & React.RefAttributes<HTMLInputElement>>>;
|
|
554
|
+
|
|
555
|
+
type TRadio = RadioProps & TDefaultFieldType & {
|
|
556
|
+
options: {
|
|
557
|
+
value: string;
|
|
558
|
+
label: string;
|
|
559
|
+
}[];
|
|
560
|
+
};
|
|
561
|
+
declare const Radio: React.ForwardRefExoticComponent<Omit<TRadio, "ref"> & React.RefAttributes<HTMLInputElement>>;
|
|
562
|
+
|
|
563
|
+
type TSelect = SelectProps & TDefaultFieldType & {
|
|
564
|
+
options: {
|
|
565
|
+
value: string;
|
|
566
|
+
label: string;
|
|
567
|
+
}[];
|
|
568
|
+
};
|
|
569
|
+
declare const Select: React.ForwardRefExoticComponent<Omit<TSelect, "ref"> & React.RefAttributes<HTMLSelectElement>>;
|
|
570
|
+
|
|
571
|
+
type TSwitchbox = Omit<SwitchProps, 'onChange'> & Pick<InputProps, 'onChange'> & TDefaultFieldType & {
|
|
572
|
+
reverse?: boolean;
|
|
573
|
+
};
|
|
574
|
+
declare const Switchbox: React.ForwardRefExoticComponent<Omit<TSwitchbox, "ref"> & React.RefAttributes<HTMLInputElement>>;
|
|
575
|
+
|
|
576
|
+
type TTextarea = TextareaProps & TDefaultFieldType;
|
|
577
|
+
declare const Textarea: React.ForwardRefExoticComponent<Omit<TTextarea, "ref"> & React.RefAttributes<HTMLTextAreaElement>>;
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Renderiza los errores del campo con el nombre pasado
|
|
581
|
+
* como prop. En caso de que no exista error, no renderiza
|
|
582
|
+
* nada.
|
|
583
|
+
*
|
|
584
|
+
* @props
|
|
585
|
+
* *name:* El nombre del campo cuyos errores se quieren
|
|
586
|
+
* renderizar.
|
|
587
|
+
*/
|
|
588
|
+
declare const ValidationError: ({ name }: {
|
|
589
|
+
name: string;
|
|
590
|
+
}) => theme_ui_jsx_runtime.JSX.Element | null;
|
|
591
|
+
|
|
592
|
+
declare function useFieldStatesClassNames<T = unknown>(name: string, formName?: string): string;
|
|
593
|
+
|
|
594
|
+
interface IUseFieldValue {
|
|
595
|
+
formName?: string;
|
|
596
|
+
name: string;
|
|
597
|
+
}
|
|
598
|
+
declare function useFieldValue<T = unknown>({ formName, name }: IUseFieldValue): T;
|
|
599
|
+
|
|
600
|
+
declare function useValidationClass<T>({ customValidation, validationClass, validationFunction, validationRules, }: Pick<TDefaultFieldType<T>, 'validationClass' | 'validationFunction' | 'validationRules'> & {
|
|
601
|
+
customValidation?: TValidationFunction<T>;
|
|
602
|
+
}): {
|
|
603
|
+
actualValidationFunction: TValidationFunction<T>;
|
|
604
|
+
actualValidationRules: {
|
|
605
|
+
number?: boolean | undefined;
|
|
606
|
+
required?: boolean | undefined;
|
|
607
|
+
alpha?: boolean | undefined;
|
|
608
|
+
alphanum?: boolean | undefined;
|
|
609
|
+
nodigit?: boolean | undefined;
|
|
610
|
+
digit?: boolean | undefined;
|
|
611
|
+
email?: boolean | undefined;
|
|
612
|
+
image?: boolean | undefined;
|
|
613
|
+
phone?: boolean | undefined;
|
|
614
|
+
url?: boolean | undefined;
|
|
615
|
+
lengthmax?: boolean | undefined;
|
|
616
|
+
lengthmin?: boolean | undefined;
|
|
617
|
+
checkbox?: boolean | undefined;
|
|
618
|
+
radios?: boolean | undefined;
|
|
619
|
+
select?: boolean | undefined;
|
|
620
|
+
select_multiple?: boolean | undefined;
|
|
621
|
+
errorsTitle?: boolean | undefined;
|
|
622
|
+
digitmin?: number | undefined;
|
|
623
|
+
digitltd?: [number, number] | undefined;
|
|
624
|
+
confirm?: string | undefined;
|
|
625
|
+
differs?: string | undefined;
|
|
626
|
+
length_str?: [number, number] | undefined;
|
|
627
|
+
length_fix?: number | undefined;
|
|
628
|
+
words_min?: number | undefined;
|
|
629
|
+
words_max?: number | undefined;
|
|
630
|
+
words_range?: [number, number] | undefined;
|
|
631
|
+
checkboxes_group?: number | undefined;
|
|
632
|
+
patternMessage?: string | undefined;
|
|
633
|
+
pattern?: string | RegExp | undefined;
|
|
634
|
+
digitmax?: number | undefined;
|
|
635
|
+
validName?: string | undefined;
|
|
636
|
+
maxLength?: number | undefined;
|
|
637
|
+
minLength?: number | undefined;
|
|
638
|
+
min?: number | undefined;
|
|
639
|
+
max?: number | undefined;
|
|
640
|
+
};
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
export { Checkbox, DeletableInput, FieldLabel, FieldWrapper, FileInput, Form, FormContext, IWrapper, Input, NumberInputf, Radio, Select, Switchbox, TCheckbox, TDefaultFieldType, TFieldLabel, TInput$1 as TInput, TRadio, TSelect, TSwitchbox, TUseField, Textarea, ValidationError, classToValidate, classToValidationFunction, hasSucceedFieldValidation, hasSucceedFormValidation, initValidations, useField, useFieldSelector, useFieldStatesClassNames, useFieldValue, useFormContext, useFormSelector, useValidationClass, validationsStore };
|