@mui/x-date-pickers
Version:
The community edition of the Date and Time Picker components (MUI X).
54 lines (53 loc) • 2.21 kB
JavaScript
'use client';
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import { useLocalizationContext } from "../internals/hooks/useUtils.js";
/**
* Utility hook to check if a given value is valid based on the provided validation props.
* @template TDate
* @template TValue The value type. It will be either the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {UseValidationOptions<TValue, TDate, TError, TValidationProps>} options The options to configure the hook.
* @param {TValue} options.value The value to validate.
* @param {PickersTimezone} options.timezone The timezone to use for the validation.
* @param {Validator<TValue, TDate, TError, TValidationProps>} options.validator The validator function to use.
* @param {TValidationProps} options.props The validation props, they differ depending on the component.
* @param {(error: TError, value: TValue) => void} options.onError Callback fired when the error associated with the current value changes.
*/
export function useValidation(options) {
const {
props,
validator,
value,
timezone,
onError
} = options;
const adapter = useLocalizationContext();
const previousValidationErrorRef = React.useRef(validator.valueManager.defaultErrorState);
const validationError = validator({
adapter,
value,
timezone,
props
});
const hasValidationError = validator.valueManager.hasError(validationError);
React.useEffect(() => {
if (onError && !validator.valueManager.isSameError(validationError, previousValidationErrorRef.current)) {
onError(validationError, value);
}
previousValidationErrorRef.current = validationError;
}, [validator, onError, validationError, value]);
const getValidationErrorForNewValue = useEventCallback(newValue => {
return validator({
adapter,
value: newValue,
timezone,
props
});
});
return {
validationError,
hasValidationError,
getValidationErrorForNewValue
};
}