-
Notifications
You must be signed in to change notification settings - Fork 834
/
useValidation.ts
28 lines (24 loc) · 914 Bytes
/
useValidation.ts
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
import * as React from 'react';
import { useUtils, MuiPickersAdapter } from './useUtils';
export interface ValidationProps<TError, TDateValue> {
/** Callback fired when new error should be displayed
* (!! This is a side effect. Be careful if you want to rerender the component) @DateIOType
*/
onError?: (reason: TError | null, value: TDateValue) => void;
}
export function makeValidationHook<
TError,
TDateValue,
TProps extends ValidationProps<TError, TDateValue>
>(validateFn: (utils: MuiPickersAdapter, value: TDateValue, props: TProps) => TError | null) {
return (value: TDateValue, props: TProps) => {
const utils = useUtils();
const validationError = validateFn(utils, value, props);
React.useEffect(() => {
if (props.onError) {
props.onError(validationError, value);
}
}, [props, validationError, value]);
return validationError !== null;
};
}