Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@daniele-zurico
Created July 10, 2019 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniele-zurico/c3bef3fa48d2d9cf266070138d9f4066 to your computer and use it in GitHub Desktop.
Save daniele-zurico/c3bef3fa48d2d9cf266070138d9f4066 to your computer and use it in GitHub Desktop.
index.js
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