Skip to content

Commit

Permalink
feat(input): prevent input of [eE] characters (#1422)
Browse files Browse the repository at this point in the history
* feat(input): prevent input of [eE] characters
  • Loading branch information
fulcanellee authored Dec 26, 2024
1 parent 8078fe2 commit 32f3aac
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/cool-melons-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@alfalab/core-components-input': minor
---

Запрещен ввод и вставка символов `[eE]` в input[type=number]
40 changes: 38 additions & 2 deletions packages/input/src/components/base-input/Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import React, {
Fragment,
HTMLAttributes,
InputHTMLAttributes,
KeyboardEvent,
MouseEvent,
ReactNode,
RefAttributes,
Expand Down Expand Up @@ -268,6 +269,7 @@ export const BaseInput = React.forwardRef<HTMLInputElement, BaseInputProps>(
},
ref,
) => {
const { onKeyDown } = restProps;
const uncontrolled = value === undefined;
const readOnly = readOnlyProp || disableUserInput;

Expand Down Expand Up @@ -327,17 +329,50 @@ export const BaseInput = React.forwardRef<HTMLInputElement, BaseInputProps>(

const handleInputChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
let inputValue = event.target.value;
const target = event.target as HTMLInputElement;
const isInputTypeNumber = target.getAttribute('type') === 'number';
const pattern = /[eE]/g;

if (isInputTypeNumber && pattern.test(inputValue)) {
inputValue = inputValue.replace(pattern, '');
}

if (onChange) {
onChange(event, { value: event.target.value });
onChange(event, { value: inputValue });
}

if (uncontrolled) {
setStateValue(event.target.value);
setStateValue(inputValue);
}
},
[onChange, uncontrolled],
);

const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLInputElement>) => {
/**
* По умолчанию в input[type=number] можно вводить числа типа 2e5 (200 000)
* Это ломает некоторое поведение, поэтому запрещаем ввод символов [eE]
* @see DS-6808
*/
const { key, target } = event;
const eventTarget = target as HTMLInputElement;
const isInputTypeNumber = eventTarget.getAttribute('type') === 'number';

if (isInputTypeNumber && (key === 'e' || key === 'E')) {
event.preventDefault();

return;
}

if (onKeyDown) {
onKeyDown(event);
}
},
[onKeyDown],
);

const handleClear = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
if (!clearButtonVisible) return;
Expand Down Expand Up @@ -457,6 +492,7 @@ export const BaseInput = React.forwardRef<HTMLInputElement, BaseInputProps>(
onBlur={handleInputBlur}
onFocus={handleInputFocus}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onAnimationStart={handleAnimationStart}
ref={mergeRefs([ref, inputRef])}
type={type}
Expand Down

0 comments on commit 32f3aac

Please sign in to comment.