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 } from '@mantine/core';
import { useValidatedState } from '@mantine/hooks';
function Demo() {
const [{ value, lastValidValue, valid }, setEmail] = useValidatedState(
'',
(val) => /^\S+@\S+$/.test(val),
true
);
return (
<div style={{ maxWidth: 320, margin: 'auto' }}>
<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>
</div>
);
}

Definition

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