Skip to content

Commit c015c58

Browse files
committed
feat: update type prop
1 parent fb9d540 commit c015c58

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

src/index.tsx

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export interface ReactInputVerificationCodeProps {
1818
placeholder?: string;
1919
value?: string;
2020
dataCy?: string;
21-
type?: 'text' | 'password';
21+
type?: 'alphanumeric' | 'number';
2222
}
2323

2424
const ReactInputVerificationCode = ({
@@ -29,8 +29,8 @@ const ReactInputVerificationCode = ({
2929
placeholder = '·',
3030
// value: pValue,
3131
dataCy = 'verification-code',
32-
}: // type = 'text',
33-
ReactInputVerificationCodeProps) => {
32+
type = 'number',
33+
}: ReactInputVerificationCodeProps) => {
3434
const [values, setValues] = useState(new Array(length).fill(placeholder));
3535

3636
const [focusedIndex, setFocusedIndex] = useState<number>(-1);
@@ -53,6 +53,28 @@ ReactInputVerificationCodeProps) => {
5353
// blurItem(activeIndex);
5454
// };
5555

56+
const validate = (input: string) => {
57+
if (type === 'number') {
58+
return /^\d$/.test(input);
59+
}
60+
61+
if (type === 'alphanumeric') {
62+
return /^[a-zA-Z0-9]$/.test(input);
63+
}
64+
65+
return true;
66+
};
67+
68+
const selectInputContent = (index: number) => {
69+
const input = inputsRefs[index].current;
70+
71+
if (input) {
72+
requestAnimationFrame(() => {
73+
input.select();
74+
});
75+
}
76+
};
77+
5678
const setValue = (value: string, index: number) => {
5779
const nextValues = [...values];
5880
nextValues[index] = value;
@@ -95,7 +117,7 @@ ReactInputVerificationCodeProps) => {
95117

96118
if (input) {
97119
setFocusedIndex(index);
98-
input.select();
120+
selectInputContent(index);
99121
}
100122
};
101123

@@ -110,6 +132,15 @@ ReactInputVerificationCodeProps) => {
110132
*/
111133
const value = eventValue.replace(values[index], '');
112134

135+
/**
136+
* if the value is not valid, don't go any further
137+
* and select the content of the input for a better UX
138+
*/
139+
if (!validate(value)) {
140+
selectInputContent(index);
141+
return;
142+
}
143+
113144
setValue(value, index);
114145

115146
/**

0 commit comments

Comments
 (0)