Created
July 10, 2019 10:29
-
-
Save daniele-zurico/c3bef3fa48d2d9cf266070138d9f4066 to your computer and use it in GitHub Desktop.
index.js
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 {Rule} from '@cesium133/forgjs' | |
interface Validation { | |
rule: any | |
message: string | |
} | |
const useValidation = (value: string, validation: Validation) => { | |
const [validity, setValid] = React.useState({valid: true, message: ''}) | |
const floatRule: any = new Rule(validation.rule, validation.message) | |
const valid = floatRule.test(parseFloat(value)) | |
setValid({ | |
valid, | |
message: floatRule.error, | |
}) | |
return { | |
validity, | |
setValid, | |
} | |
} | |
export default useValidation | |
///////// | |
import React from 'react' | |
import {useValidation} from '../common' | |
interface FormInputProps { | |
name: string | |
type: string | |
value: any | |
validation: { | |
rule: any | |
message: string | |
} | |
onChange: (event: React.FormEvent<HTMLInputElement>, valid: boolean) => void | |
} | |
const FormInput: React.FC<FormInputProps> = ({ | |
name, | |
type, | |
value, | |
validation, | |
onChange, | |
}) => { | |
const inputEl = React.useRef<HTMLInputElement | null>(null) | |
const {validity} = useValidation( | |
inputEl.current ? inputEl.current.value : '', | |
validation, | |
) | |
const handleChange = (event: React.FormEvent<HTMLInputElement>) => { | |
onChange(event, validity.valid) | |
} | |
return ( | |
<div style={{width: '97%', marginBottom: '15px'}}> | |
<input style={{width: '100%'}} name={name} type={type} value={value} /> | |
{validity.valid && ( | |
<div | |
style={{ | |
fontSize: '10px', | |
color: 'red', | |
fontWeight: 'bold', | |
}} | |
onChange={handleChange} | |
> | |
{validity.message} | |
</div> | |
)} | |
</div> | |
) | |
} | |
export default FormInput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment