-
Notifications
You must be signed in to change notification settings - Fork 0
/
useInput.ts
89 lines (78 loc) · 2.46 KB
/
useInput.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { useEffect, useState } from 'react';
/**
* Represents the shape of the state object returned by the useInput hook.
*/
type InputState = {
/** The current value of the input field. */
value: string;
/** Indicates whether the input field is currently focused. */
focus: boolean;
/** Event handler for input changes. */
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
/** Event handler for input blur. */
onBlur: () => void;
/** Event handler for input focus. */
onFocus: () => void;
/** Indicates whether there is an error in the input value. */
hasError: boolean;
};
/**
* A custom React hook for managing the state of an input field.
* @param validate A function to validate the input value.
* @returns An object containing input state and event handlers.
*/
export const useInput = (validate: (value: string) => boolean): InputState => {
const [value, setValue] = useState<string>('');
const [touched, setTouched] = useState<boolean>(false);
const [focus, setFocus] = useState<boolean>(false);
const isValid: boolean = validate(value);
const hasError: boolean = !isValid && touched;
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
};
const onBlur = (): void => {
setTouched(true);
!value && setFocus(false);
};
const onFocus = (): void => {
setFocus(true);
};
useEffect(() => {
value && setFocus(true);
}, [value]);
return {
value,
focus,
onChange,
onBlur,
onFocus,
hasError,
};
};
// Example usage
// Email Input
// const {
// value: emailValue,
// focus: emailFocus,
// hasError: emailHasError,
// onChange: emailOnChange,
// onBlur: emailOnBlur,
// onFocus: emailOnFocus,
// } = useInput((email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email));
// Phone Input
// const {
// value: phoneValue,
// focus: phoneFocus,
// hasError: phoneHasError,
// onChange: phoneOnChange,
// onBlur: phoneOnBlur,
// onFocus: phoneOnFocus,
// } = useInput((phone: string) => {
// const phoneRegex = /^(\+\d{3}\s?)?\(?[\s.-]?\d{3}\)?[\s.-]?\d{2}[\s.-]?\d{2}[\s.-]?\d{2}$/;
// const phoneRegexVol2 = /^(\+\d{3}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{3}$/;
// const sanitizedPhone = phone.replace(/[-\s]/g, '');
// const shortPhoneRegex = /^\d{9}$/;
// return (
// phoneRegex.test(phone) || phoneRegexVol2.test(phone) || shortPhoneRegex.test(sanitizedPhone)
// );
// });