Created
October 18, 2019 00:20
-
-
Save Chrispassold/b55ddf5d4d0c0ea37664718ec8d7f25b to your computer and use it in GitHub Desktop.
Time input with validation and simple mask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Input } from 'semantic-ui-react'; | |
class TimeInput extends React.Component { | |
state = { | |
time: '', | |
} | |
handleChange = (event, { name, value }) => { | |
value = value.replace(":", "") | |
if (value.length > 4) | |
return | |
const values = value.split("") | |
var formated = "" | |
values.forEach((element) => { | |
if (formated.length === 2) | |
formated += ":" | |
formated += element | |
}) | |
var isValid = false; | |
formated.split(":").forEach((element, index) => { | |
const padded = this.padZero(element) | |
if (index === 0 && Number(padded) <= 23) { | |
isValid = true | |
} else if (index === 1 && Number(padded) <= 59) { | |
isValid = true | |
} else { | |
isValid = false | |
} | |
}) | |
if (isValid && this.state.hasOwnProperty(name)) { | |
this.setState({ [name]: formated }); | |
} | |
} | |
padZero = (num) => { | |
var s = num + ""; | |
while (s.length < 2) s = s + "0"; | |
return s; | |
} | |
checkNumber = (event) => { | |
if (!/[0123456789:]/.test(String.fromCharCode(event.which))) { | |
event.preventDefault() | |
} | |
} | |
render() { | |
return <Input | |
icon="time" | |
name="time" | |
placeholder='00:00' | |
value={this.state.time} | |
onChange={this.handleChange} | |
onKeyPress={this.checkNumber} | |
/> | |
} | |
} | |
export default TimeInput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment