Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement