Skip to content

Commit

Permalink
Validate 'Add' input value
Browse files Browse the repository at this point in the history
  • Loading branch information
vijexa committed Dec 2, 2023
1 parent 6cb3b6d commit 783de18
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/TimeInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,27 @@ interface TimeInputProps {

export function TimeInput({ onTimeChange }: TimeInputProps) {

const [inputValue, setInputValue] = useState(1);
const [inputValue, setInputValue] = useState('1');
const [prevValue, setPrevValue] = useState('1');

const addTime = (unit: Units) => () => {
onTimeChange(unit, inputValue);
onTimeChange(unit, parseInt(inputValue));
};


// making sure there is a valid value on blur
function onFieldBlur() {
const parsedValue = parseInt(inputValue);
if (isNaN(parsedValue) || parsedValue === 0) {
setInputValue(prevValue);
} else {
// format the value to remove leading zeroes (if any)
const asString = parsedValue.toString();
setPrevValue(asString);
setInputValue(asString);
}
}

return (
<>
<Stack
Expand All @@ -36,7 +51,8 @@ export function TimeInput({ onTimeChange }: TimeInputProps) {
width: '80px',
}}
value={inputValue}
onChange={(event) => setInputValue(parseInt(event.target.value))}
onChange={(event) => setInputValue(event.target.value)}
onBlur={onFieldBlur}
/>
<ButtonGroup variant="outlined">
<Button onClick={addTime('hours')}>Hours</Button>
Expand All @@ -46,3 +62,5 @@ export function TimeInput({ onTimeChange }: TimeInputProps) {
</>
);
}


0 comments on commit 783de18

Please sign in to comment.