Skip to content

Instantly share code, notes, and snippets.

@shalithasuranga
Created January 26, 2022 17:40
Show Gist options
  • Save shalithasuranga/43c36a3e3d78ba31d94400ecc7b75cb0 to your computer and use it in GitHub Desktop.
Save shalithasuranga/43c36a3e3d78ba31d94400ecc7b75cb0 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
import InputMask from 'react-input-mask';
function TimeInput(props) {
let mask = 'dD-mM-YYYY';
let formatChars = {
'Y': '[0-9]',
'd': '[0-3]',
'D': '[0-9]',
'm': '[0-1]',
'M': '[1-9]'
};
let beforeMaskedValueChange = (newState, oldState, userInput) => {
let { value } = newState;
let dateParts = value.split('-');
let dayPart = dateParts[0];
let monthPart = dateParts[1];
// Conditional mask for the 2nd digit of day based on the first digit
if(dayPart.startsWith('3'))
formatChars['D'] = '[0-1]'; // To block 39, 32, etc.
else if(dayPart.startsWith('0'))
formatChars['D'] = '[1-9]'; // To block 00.
else
formatChars['D'] = '[0-9]'; // To allow 05, 15, 25 etc.
// Conditional mask for the 2nd digit of month based on the first digit
if(monthPart.startsWith('1'))
formatChars['M'] = '[0-2]'; // To block 15, 16, etc.
else
formatChars['M'] = '[1-9]'; // To allow 05, 06 etc - but blocking 00.
return {value, selection: newState.selection};
}
return (
<InputMask
mask={mask}
value={props.value}
onChange={props.onChange}
formatChars={formatChars}
beforeMaskedValueChange={beforeMaskedValueChange}>
</InputMask>
);
}
function App() {
const [date, setDate] = useState('');
const handleInput = ({ target: { value } }) => setDate(value);
return (
<div>
<TimeInput
value={date}
onChange={handleInput}>
</TimeInput>
<div style={{paddingTop: '12px'}}>Date: {date}</div>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment