Skip to content

Commit

Permalink
refactor: move validate function outside render
Browse files Browse the repository at this point in the history
  • Loading branch information
amje committed Jun 10, 2024
1 parent 41b0583 commit 83bfaa5
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/components/PinInput/PinInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ const b = block('pin-input');
const NUMERIC_REGEXP = /[0-9]+/;
const ALPHANUMERIC_REGEXP = /[0-9a-z]+/i;

const validate = (type: PinInputType, newValue: string) => {
if (type === 'numeric') {
return NUMERIC_REGEXP.test(newValue);
} else {
return ALPHANUMERIC_REGEXP.test(newValue);
}
};

export const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>((props, ref) => {
const {
value,
Expand Down Expand Up @@ -117,14 +125,6 @@ export const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>((props,
}
};

const validate = (newValue: string) => {
if (type === 'numeric') {
return NUMERIC_REGEXP.test(newValue);
} else {
return ALPHANUMERIC_REGEXP.test(newValue);
}
};

const setValuesAtIndex = (index: number, nextValue: string) => {
// Normalize array size to length prop
const newValues = Array.from({length}, (__, i) => values[i] ?? '');
Expand Down Expand Up @@ -159,7 +159,7 @@ export const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>((props,
}
}

if (!validate(nextValue)) {
if (!validate(type, nextValue)) {
return;
}

Expand Down

0 comments on commit 83bfaa5

Please sign in to comment.