forked from jaredpalmer/formik
/
formik.tsx
654 lines (586 loc) · 18.9 KB
/
formik.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import * as PropTypes from 'prop-types';
import * as React from 'react';
import isEqual from 'lodash.isequal';
import set from 'lodash/set';
import cloneDeep from 'lodash/cloneDeep';
import { isFunction, isPromise, isReactNative, values } from './utils';
import warning from 'warning';
/**
* Values of fields in the form
*/
export interface FormikValues {
[field: string]: any;
}
/**
* An object containing error messages whose keys correspond to FormikValues.
*/
export type FormikErrors = {
[field: string]: string;
};
/**
* An object containing touched state of the form whose keys correspond to FormikValues.
*/
export type FormikTouched = {
[field: string]: boolean;
};
/**
* Formik state tree
*/
export interface FormikState<Values> {
/** Form values */
values: Values;
/**
* Top level error, in case you need it
* @deprecated since 0.8.0
*/
error?: any;
/** map of field names to specific error for that field */
errors: FormikErrors;
/** map of field names to whether the field has been touched */
touched: FormikTouched;
/** whether the form is currently submitting */
isSubmitting: boolean;
/** Top level status state, in case you need it */
status?: any;
}
/**
* Formik computed properties. These are read-only.
*/
export interface FormikComputedProps<Values> {
/** True if any input has been touched. False otherwise. */
readonly dirty: boolean;
/** Result of isInitiallyValid on mount, then whether true values pass validation. */
readonly isValid: boolean;
/** initialValues */
readonly initialValues: Values;
}
/**
* Formik state helpers
*/
export interface FormikActions<Values> {
/** Manually set top level status. */
setStatus: (status?: any) => void;
/**
* Manually set top level error
* @deprecated since 0.8.0
*/
setError: (e: any) => void;
/** Manually set errors object */
setErrors: (errors: FormikErrors) => void;
/** Manually set isSubmitting */
setSubmitting: (isSubmitting: boolean) => void;
/** Manually set touched object */
setTouched: (touched: FormikTouched) => void;
/** Manually set values object */
setValues: (values: Values) => void;
/** Set value of form field directly */
setFieldValue: (field: keyof Values, value: any) => void;
/** Set error message of a form field directly */
setFieldError: (field: keyof Values, message: string) => void;
/** Set whether field has been touched directly */
setFieldTouched: (field: keyof Values, isTouched?: boolean) => void;
/** Reset form */
resetForm: (nextValues?: any) => void;
/** Submit the form imperatively */
submitForm: () => void;
}
/**
* Formik form event handlers
*/
export interface FormikHandlers {
/** Form submit handler */
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
/** Classic React change handler, keyed by input name */
handleChange: (e: React.ChangeEvent<any>) => void;
/** Mark input as touched */
handleBlur: (e: any) => void;
/** Change value of form field directly */
handleChangeValue: (name: string, value: any) => void;
/** Reset form event handler */
handleReset: () => void;
}
/**
* Base formik configuration/props shared between the HoC and Component.
*/
export interface FormikSharedConfig {
/** Tells Formik to validate the form on each input's onChange event */
validateOnChange?: boolean;
/** Tells Formik to validate the form on each input's onBlur event */
validateOnBlur?: boolean;
/** Tell Formik if initial form values are valid or not on first render */
isInitialValid?: boolean | ((props: object) => boolean | undefined);
/** Should Formik reset the form when new initialValues change */
enableReinitialize?: boolean;
}
/**
* <Formik /> props
*/
export interface FormikConfig extends FormikSharedConfig {
/**
* Initial values of the form
*/
initialValues: object;
/**
* Submission handler
*/
onSubmit: (values: object, formikActions: FormikActions<any>) => void;
/**
* Form component to render
*/
component?: React.ComponentType<FormikProps<any> | void>;
/**
* Render prop (works like React router's <Route render={props =>} />)
*/
render?: ((props: FormikProps<any>) => React.ReactNode);
/**
* A Yup Schema or a function that returns a Yup schema
*/
validationSchema?: any | (() => any);
/**
* Validation function. Must return an error object or promise that
* throws an error object where that object keys map to corresponding value.
*/
validate?: ((values: any) => void | object | Promise<any>);
/**
* React children or child render callback
*/
children?: ((props: FormikProps<any>) => React.ReactNode) | React.ReactNode;
}
/**
* State, handlers, and helpers made available to form component or render prop
* of <Formik/>.
*/
export type FormikProps<Values> = FormikState<Values> &
FormikActions<Values> &
FormikHandlers &
FormikComputedProps<Values>;
const isEmptyChildren = (children: any) => React.Children.count(children) === 0;
export class Formik<
Props extends FormikConfig = FormikConfig
> extends React.Component<Props, FormikState<any>> {
static defaultProps = {
validateOnChange: true,
validateOnBlur: true,
isInitialValid: false,
enableReinitialize: false,
};
static propTypes = {
validateOnChange: PropTypes.bool,
validateOnBlur: PropTypes.bool,
isInitialValid: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
initialValues: PropTypes.object,
onSubmit: PropTypes.func.isRequired,
validationSchema: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
validate: PropTypes.func,
component: PropTypes.func,
render: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
enableReinitialize: PropTypes.bool,
};
static childContextTypes = {
formik: PropTypes.object,
};
initialValues: any;
getChildContext() {
const dirty =
values<boolean>(this.state.touched).filter(Boolean).length > 0;
return {
formik: {
...this.state,
dirty,
isValid: dirty
? this.state.errors && Object.keys(this.state.errors).length === 0
: this.props.isInitialValid !== false &&
isFunction(this.props.isInitialValid)
? (this.props.isInitialValid as (props: Props) => boolean)(
this.props
)
: this.props.isInitialValid as boolean,
handleSubmit: this.handleSubmit,
handleChange: this.handleChange,
handleBlur: this.handleBlur,
handleReset: this.handleReset,
setStatus: this.setStatus,
setTouched: this.setTouched,
setErrors: this.setErrors,
setError: this.setError,
setValues: this.setValues,
setFieldError: this.setFieldError,
setFieldValue: this.setFieldValue,
setFieldTouched: this.setFieldTouched,
setSubmitting: this.setSubmitting,
resetForm: this.resetForm,
submitForm: this.submitForm,
initialValues: this.initialValues,
},
};
}
constructor(props: Props) {
super(props);
this.state = {
values: props.initialValues || ({} as any),
errors: {},
touched: {},
isSubmitting: false,
};
this.initialValues = props.initialValues || ({} as any);
}
componentWillReceiveProps(nextProps: Props) {
// If the initialValues change, reset the form
if (
this.props.enableReinitialize &&
!isEqual(nextProps.initialValues, this.props.initialValues)
) {
this.initialValues = nextProps.initialValues;
this.resetForm(nextProps.initialValues);
}
}
componentWillMount() {
warning(
!(this.props.component && this.props.render),
'You should not use <Formik component> and <Formik render> in the same <Formik> component; <Formik render> will be ignored'
);
warning(
!(
this.props.component &&
this.props.children &&
!isEmptyChildren(this.props.children)
),
'You should not use <Formik component> and <Formik children> in the same <Formik> component; <Formik children> will be ignored'
);
warning(
!(
this.props.render &&
this.props.children &&
!isEmptyChildren(this.props.children)
),
'You should not use <Formik render> and <Formik children> in the same <Formik> component; <Formik children> will be ignored'
);
}
setErrors = (errors: FormikErrors) => {
this.setState({ errors });
};
setTouched = (touched: FormikTouched) => {
this.setState({ touched }, () => {
if (this.props.validateOnBlur) {
this.runValidations(this.state.values);
}
});
};
setValues = (values: FormikValues) => {
this.setState({ values }, () => {
if (this.props.validateOnChange) {
this.runValidations(values);
}
});
};
setStatus = (status?: any) => {
this.setState({ status });
};
setError = (error: any) => {
if (process.env.NODE_ENV !== 'production') {
console.warn(
`Warning: Formik\'s setError(error) is deprecated and may be removed in future releases. Please use Formik\'s setStatus(status) instead. It works identically. For more info see https://github.com/jaredpalmer/formik#setstatus-status-any--void`
);
}
this.setState({ error });
};
setSubmitting = (isSubmitting: boolean) => {
this.setState({ isSubmitting });
};
/**
* Run validation against a Yup schema and optionally run a function if successful
*/
runValidationSchema = (values: FormikValues, onSuccess?: Function) => {
const { validationSchema } = this.props;
const schema = isFunction(validationSchema)
? validationSchema()
: validationSchema;
validateYupSchema(values, schema).then(
() => {
this.setState({ errors: {} });
if (onSuccess) {
onSuccess();
}
},
(err: any) =>
this.setState({ errors: yupToFormErrors(err), isSubmitting: false })
);
};
/**
* Run validations and update state accordingly
*/
runValidations = (values: FormikValues) => {
if (this.props.validationSchema) {
this.runValidationSchema(values);
}
if (this.props.validate) {
const maybePromisedErrors = (this.props.validate as any)(values);
if (isPromise(maybePromisedErrors)) {
(maybePromisedErrors as Promise<any>).then(
() => {
this.setState({ errors: {} });
},
errors => this.setState({ errors, isSubmitting: false })
);
} else {
this.setErrors(maybePromisedErrors as FormikErrors);
}
}
};
handleChange = (e: React.ChangeEvent<any>) => {
if (isReactNative) {
if (process.env.NODE_ENV !== 'production') {
console.error(
`Warning: Formik's handleChange does not work with React Native. Use setFieldValue and within a callback instead. For more info see https://github.com/jaredpalmer/formikhttps://github.com/jaredpalmer/formik#react-native`
);
}
return;
}
e.persist();
const { type, name, id, value, checked, outerHTML } = e.target;
const field = name ? name : id;
const val = /number|range/.test(type)
? parseFloat(value)
: /checkbox/.test(type) ? checked : value;
if (!field && process.env.NODE_ENV !== 'production') {
console.error(
`Warning: You forgot to pass an \`id\` or \`name\` attribute to your input:
${outerHTML}
Formik cannot determine which value to update. For more info see https://github.com/jaredpalmer/formik#handlechange-e-reactchangeeventany--void
`
);
}
// Set form fields by name
this.setState(prevState => ({
...prevState,
values: set(cloneDeep(prevState.values), field, val),
}));
if (this.props.validateOnChange) {
this.runValidations(set(cloneDeep(this.state.values), field, value));
}
};
handleChangeValue = (field: string, value: any) => {
if (process.env.NODE_ENV !== 'production') {
console.warn(
`Warning: Formik\'s handleChangeValue is deprecated and may be removed in future releases. Use Formik's setFieldValue(field, value) and setFieldTouched(field, isTouched) instead. React will merge the updates under the hood and avoid a double render. For more info see https://github.com/jaredpalmer/formik#setfieldvalue-field-string-value-any--void`
);
}
// Set touched and form fields by name
this.setState(prevState => ({
...prevState,
values: set(cloneDeep(prevState.values), field, value),
touched: set(cloneDeep(prevState.touched), field, true),
}));
this.runValidationSchema(set(cloneDeep(this.state.values), field, value));
};
setFieldValue = (field: string, value: any) => {
// Set form field by name
this.setState(
prevState => ({
...prevState,
values: set(cloneDeep(prevState.values), field, value),
}),
() => {
if (this.props.validateOnChange) {
this.runValidations(set(cloneDeep(this.state.values), field, value));
}
}
);
};
handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
this.submitForm();
};
submitForm = () => {
this.setState({
touched: touchAllFields<FormikTouched>(this.state.values),
isSubmitting: true,
});
if (this.props.validate) {
const maybePromisedErrors =
(this.props.validate as any)(this.state.values) || {};
if (isPromise(maybePromisedErrors)) {
(maybePromisedErrors as Promise<any>).then(
() => {
this.setState({ errors: {} });
this.executeSubmit();
},
errors => this.setState({ errors, isSubmitting: false })
);
return;
} else {
const isValid = Object.keys(maybePromisedErrors).length === 0;
this.setState({
errors: maybePromisedErrors as FormikErrors,
isSubmitting: isValid,
});
// only submit if there are no errors
if (isValid) {
this.executeSubmit();
}
}
} else if (this.props.validationSchema) {
this.runValidationSchema(this.state.values, this.executeSubmit);
} else {
this.executeSubmit();
}
};
executeSubmit = () => {
this.props.onSubmit(this.state.values, {
resetForm: this.resetForm,
setError: this.setError,
setErrors: this.setErrors,
setFieldError: this.setFieldError,
setFieldTouched: this.setFieldTouched,
setFieldValue: this.setFieldValue,
setStatus: this.setStatus,
setSubmitting: this.setSubmitting,
setTouched: this.setTouched,
setValues: this.setValues,
submitForm: this.submitForm,
});
};
handleBlur = (e: any) => {
if (isReactNative) {
if (process.env.NODE_ENV !== 'production') {
console.error(
`Warning: Formik's handleBlur does not work with React Native. Use setFieldTouched(field, isTouched) within a callback instead. For more info see https://github.com/jaredpalmer/formik#setfieldtouched-field-string-istouched-boolean--void`
);
}
return;
}
e.persist();
const { name, id } = e.target;
const field = name ? name : id;
this.setState(prevState => ({
touched: set(cloneDeep(prevState.touched), field, true),
}));
if (this.props.validateOnBlur) {
this.runValidations(this.state.values);
}
};
setFieldTouched = (field: string, touched: boolean = true) => {
// Set touched field by name
this.setState(
prevState => ({
...prevState,
touched: set(cloneDeep(prevState.touched), field, touched),
}),
() => {
if (this.props.validateOnBlur) {
this.runValidations(this.state.values);
}
}
);
};
setFieldError = (field: string, message: string) => {
// Set form field by name
this.setState(prevState => ({
...prevState,
errors: set(cloneDeep(prevState.errors), field, message),
}));
};
resetForm = (nextValues?: any) => {
if (nextValues) {
this.initialValues = nextValues;
}
this.setState({
isSubmitting: false,
errors: {},
touched: {},
error: undefined,
status: undefined,
values: nextValues ? nextValues : this.props.initialValues,
});
};
handleReset = () => {
this.resetForm();
};
render() {
const { component, render, children, isInitialValid } = this.props;
const dirty =
values<boolean>(this.state.touched).filter(Boolean).length > 0;
const props = {
...this.state,
dirty,
isValid: dirty
? this.state.errors && Object.keys(this.state.errors).length === 0
: isInitialValid !== false && isFunction(isInitialValid)
? (isInitialValid as (props: Props) => boolean)(this.props)
: isInitialValid as boolean,
handleBlur: this.handleBlur,
handleChange: this.handleChange,
handleReset: this.handleReset,
handleSubmit: this.handleSubmit,
initialValues: this.initialValues,
resetForm: this.resetForm,
setError: this.setError,
setErrors: this.setErrors,
setFieldError: this.setFieldError,
setFieldTouched: this.setFieldTouched,
setFieldValue: this.setFieldValue,
setStatus: this.setStatus,
setSubmitting: this.setSubmitting,
setTouched: this.setTouched,
setValues: this.setValues,
submitForm: this.submitForm,
};
return component
? React.createElement(component as any, props)
: render
? (render as any)(props)
: children // children come last, always called
? typeof children === 'function'
? (children as (props: FormikProps<any>) => React.ReactNode)(
props as FormikProps<any>
)
: !isEmptyChildren(children) ? React.Children.only(children) : null
: null;
}
}
/**
* Transform Yup ValidationError to a more usable object
*/
export function yupToFormErrors(yupError: any): FormikErrors {
let errors: FormikErrors = {};
for (let err of yupError.inner) {
if (!errors[err.path]) {
set(errors, err.path, err.message);
}
}
return errors;
}
/**
* Validate a yup schema.
*/
export function validateYupSchema<T>(data: T, schema: any): Promise<void> {
let validateData: any = {};
for (let k in data) {
if (data.hasOwnProperty(k)) {
const key = String(k);
validateData[key] =
(data as any)[key] !== '' ? (data as any)[key] : undefined;
}
}
return schema.validate(validateData, { abortEarly: false });
}
function setNestedObjectValues(object: any, value: any, response: any = null) {
response = response === null ? {} : response;
for (let k of Object.keys(object)) {
const val = object[k];
if (typeof val === 'object') {
response[k] = {};
setNestedObjectValues(val, value, response[k]);
} else {
response[k] = value;
}
}
return response;
}
export function touchAllFields<T>(fields: T): FormikTouched {
return setNestedObjectValues(cloneDeep(fields), true);
}
export * from './Field';
export * from './Form';
export * from './withFormik';