62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import { ValidateStatus } from 'antd/lib/form/FormItem';
|
|
import { INVALID_INPUT as INVALID_INPUT_MESSAGE } from 'core/constants/errorMessages';
|
|
import { ElementsNames } from 'core/types/elements';
|
|
import { useEffect, useState } from 'react';
|
|
import { useStores } from './useStores';
|
|
|
|
interface IUseValidationArgs {
|
|
elementName: ElementsNames;
|
|
value: any;
|
|
validation: { errorMessage: string; validator: Function };
|
|
}
|
|
|
|
export const useValidation = ({
|
|
elementName,
|
|
value,
|
|
validation,
|
|
}: IUseValidationArgs) => {
|
|
const { validator, errorMessage } = validation || {
|
|
validator: undefined,
|
|
errorMessage: undefined,
|
|
};
|
|
const [isValid, setValidation] = useState<boolean | undefined>(undefined);
|
|
const { calculationStore } = useStores();
|
|
|
|
// inject value from store
|
|
const validationStatus = calculationStore.validations[elementName];
|
|
useEffect(() => {
|
|
setValidation(validationStatus);
|
|
}, [validationStatus]);
|
|
|
|
// inner validation && set validation status to store
|
|
useEffect(() => {
|
|
if (value === undefined || value === '') {
|
|
calculationStore.setValidation(elementName, undefined);
|
|
} else {
|
|
if (validator) {
|
|
let validationResult = validator(value);
|
|
calculationStore.setValidation(elementName, validationResult);
|
|
}
|
|
}
|
|
}, [value, validator, elementName]);
|
|
|
|
const getValidateStatus = (): ValidateStatus | undefined => {
|
|
if (isValid === undefined) {
|
|
return undefined;
|
|
}
|
|
return isValid === false ? 'error' : 'success';
|
|
};
|
|
|
|
const getMessage = (): string | undefined => {
|
|
if (isValid === false) {
|
|
return errorMessage || INVALID_INPUT_MESSAGE;
|
|
}
|
|
};
|
|
|
|
return {
|
|
isValid,
|
|
validateStatus: getValidateStatus(),
|
|
message: getMessage(),
|
|
};
|
|
};
|