Skip to content

Commit

Permalink
fix(inputs): add reset external validation
Browse files Browse the repository at this point in the history
  • Loading branch information
morewings committed Jul 27, 2024
1 parent bdab761 commit e25fcbf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
16 changes: 14 additions & 2 deletions src/internal/inputs/useExternalValidation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {Dispatch, SetStateAction, MutableRefObject} from 'react';
import {useEffect} from 'react';
import {useEffect, useState, useCallback} from 'react';

import {ValidationState} from '@/internal/inputs';

Expand All @@ -17,11 +17,17 @@ export type Props = {
* @see ValidationState
*/
export const useExternalValidation = ({
validationState,
validationState: validationStateProp,
inputRef,
setValidity,
errorMessage = ValidationState.error,
}: Props) => {
const [validationState, setValidationState] = useState(validationStateProp);

useEffect(() => {
setValidationState(validationStateProp);
}, [validationStateProp]);

useEffect(() => {
// Empty string is considered to be positive validation result for HTMLInputElement.setCustomValidity
const normalizedErrorMessage = errorMessage ? errorMessage : ValidationState.error;
Expand All @@ -33,4 +39,10 @@ export const useExternalValidation = ({
setValidity(validationState);
}
}, [errorMessage, inputRef, setValidity, validationState]);

const resetExternalValidation = useCallback(() => {
setValidationState(undefined);
}, []);

return {resetExternalValidation};
};
10 changes: 8 additions & 2 deletions src/lib/InputText/InputText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,12 @@ export const InputText = forwardRef<HTMLInputElement, Props>(
const inputRef = useInternalRef(ref);
useRevalidateOnFormChange(inputRef, validateTextual, revalidateOnFormChange);

useExternalValidation({inputRef, setValidity, validationState, errorMessage});
const {resetExternalValidation} = useExternalValidation({
inputRef,
setValidity,
validationState,
errorMessage,
});

const ValidationIcon = {
[ValidationState.error]: IconError,
Expand All @@ -82,9 +87,10 @@ export const InputText = forwardRef<HTMLInputElement, Props>(

const handleChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
resetExternalValidation();
onChange(event);
},
[onChange]
[onChange, resetExternalValidation]
);

const handleInvalid = useCallback(() => {
Expand Down

0 comments on commit e25fcbf

Please sign in to comment.