At the moment, my website has an input field into which the user can enter any characters.
According to the requirement, the field length cannot be more than 5 characters, otherwise a warning appears and nothing is allowed to be entered. It’s done!
Currently, a warning appears when entering the fifth character. But tell me: how can I make it so that the warning appears only when the user tries to enter the sixth character?
Current behavior:
The user enters the character “a” – OK
The user enters the character “b” – OK
The user enters the character “c” – OK
The user enters the character “d” – OK
The user enters the character “e” – a warning appears and user cannot enter the next symbol
Expected behavior:
The user enters the character “a” – OK
The user enters the character “b” – OK
The user enters the character “c” – OK
The user enters the character “d” – OK
The user enters the character “e” – OK
The user tries to enter the symbol “f” – the user sees a warning and cannot enter the symbol “f”
function isLength(title_) {
return title_.length < 5;
}
const Title = () => {
const [title, setTitle] = useState('');
useEffect(() => {
if (isLength(title)) {
onChange(title);
}
}, [onChange, title]);
const onChangeTitle = (event: { target: { value: string } }) => {
if (event.target.value.length < 6) {
setTitle(event.target.value.trimStart().replace(/s+/g, ' '));
}
};
let errorMessage = <div />;
if (!isLength(title)) errorMessage = <div>String at most 5 characters</div>;
return (
<div>
<input id="title" onChange={onChangeTitle} value={title} />
{errorMessage}
</div>
);
};