use-validated-state

Validate state and get last valid value
Import

Usage

use-validated-state validates state with a given rule each time state is set. It returns an object with current validation state, last valid value and current value:

const [{ lastValidValue, value, valid }, setValue] = useValidatedState(
'valid',
(value) => value === 'valid'
);
lastValidValue; // -> valid
value; // -> valid
valid; // -> true
setValue('invalid');
lastValidValue; // -> valid
value; // -> invalid
valid; // -> false

Example

Current value: [empty string]
Last valid value: [empty string]
import { TextInput, Text, Box } from '@mantine/core';
import { useValidatedState } from '@mantine/hooks';
function Demo() {
const [{ value, lastValidValue, valid }, setEmail] = useValidatedState(
'',
(val) => /^\S+@\S+$/.test(val),
true
);
return (
<Box maw={320} mx="auto" sx={{ overflowWrap: 'break-word' }}>
<TextInput
value={value}
onChange={(event) => setEmail(event.currentTarget.value)}
withAsterisk
error={!valid}
placeholder="email@example.com"
label="Your email"
/>
<Text size="sm" mt="md">
<Text inherit color="dimmed" component="span">
Current value:
</Text>{' '}
{value || '[empty string]'}
</Text>
<Text size="sm">
<Text inherit color="dimmed" component="span">
Last valid value:
</Text>{' '}
{lastValidValue || '[empty string]'}
</Text>
</Box>
);
}

Definition

function useValidatedState<T>(
initialValue: T,
validation: (value: T) => boolean,
initialValidationState?: boolean
): [
{
value: T;
lastValidValue: T;
valid: boolean;
},
(val: T) => void
];