Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import React from 'react'
  2. import {Rule} from '@cesium133/forgjs'
  3.  
  4. interface Validation {
  5. rule: any
  6. message: string
  7. }
  8.  
  9. const useValidation = (value: string, validation: Validation) => {
  10. const [validity, setValid] = React.useState({valid: true, message: ''})
  11. const floatRule: any = new Rule(validation.rule, validation.message)
  12. const valid = floatRule.test(parseFloat(value))
  13. setValid({
  14. valid,
  15. message: floatRule.error,
  16. })
  17.  
  18. return {
  19. validity,
  20. setValid,
  21. }
  22. }
  23.  
  24. export default useValidation
  25.  
  26.  
  27. /////////
  28. import React from 'react'
  29. import {useValidation} from '../common'
  30.  
  31. interface FormInputProps {
  32. name: string
  33. type: string
  34. value: any
  35. validation: {
  36. rule: any
  37. message: string
  38. }
  39. onChange: (event: React.FormEvent<HTMLInputElement>, valid: boolean) => void
  40. }
  41.  
  42. const FormInput: React.FC<FormInputProps> = ({
  43. name,
  44. type,
  45. value,
  46. validation,
  47. onChange,
  48. }) => {
  49. const inputEl = React.useRef<HTMLInputElement | null>(null)
  50.  
  51. const {validity} = useValidation(
  52. inputEl.current ? inputEl.current.value : '',
  53. validation,
  54. )
  55.  
  56. const handleChange = (event: React.FormEvent<HTMLInputElement>) => {
  57. onChange(event, validity.valid)
  58. }
  59.  
  60. return (
  61. <div style={{width: '97%', marginBottom: '15px'}}>
  62. <input style={{width: '100%'}} name={name} type={type} value={value} />
  63. {validity.valid && (
  64. <div
  65. style={{
  66. fontSize: '10px',
  67. color: 'red',
  68. fontWeight: 'bold',
  69. }}
  70. onChange={handleChange}
  71. >
  72. {validity.message}
  73. </div>
  74. )}
  75. </div>
  76. )
  77. }
  78.  
  79. export default FormInput
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement