70 lines
1.7 KiB
TypeScript
70 lines
1.7 KiB
TypeScript
import CustomTextField from "./CustomTextField";
|
|
|
|
import type { ChangeEvent, KeyboardEvent, FocusEvent } from "react";
|
|
import type { SxProps, Theme } from "@mui/material";
|
|
|
|
interface CustomNumberFieldProps {
|
|
placeholder: string;
|
|
onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
|
|
onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
|
|
onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
|
|
error?: string;
|
|
emptyError?: boolean;
|
|
value: string;
|
|
sx?: SxProps<Theme>;
|
|
min?: number;
|
|
max?: number;
|
|
}
|
|
|
|
export default function CustomNumberField({
|
|
placeholder,
|
|
value,
|
|
sx,
|
|
error,
|
|
emptyError,
|
|
onChange,
|
|
onKeyDown,
|
|
onBlur,
|
|
min = -999999999,
|
|
max = 999999999,
|
|
}: CustomNumberFieldProps) {
|
|
const onInputChange = (event: ChangeEvent<HTMLInputElement>) => {
|
|
const inputValue = event.target.value;
|
|
|
|
if (
|
|
inputValue === "" ||
|
|
inputValue.match(/^\d*$/) ||
|
|
(inputValue[0] === "-" && inputValue.slice(1).match(/^\d*$/))
|
|
) {
|
|
onChange?.({ ...event, target: { ...event.target, value: inputValue } });
|
|
}
|
|
};
|
|
|
|
const onInputBlur = (event: FocusEvent<HTMLInputElement>) => {
|
|
const inputValue = event.target.value;
|
|
|
|
if (Number(inputValue) < min) {
|
|
onChange?.({ ...event, target: { ...event.target, value: String(min) } });
|
|
}
|
|
|
|
if (Number(inputValue) > max) {
|
|
onChange?.({ ...event, target: { ...event.target, value: String(max) } });
|
|
}
|
|
|
|
onBlur?.(event);
|
|
};
|
|
|
|
return (
|
|
<CustomTextField
|
|
placeholder={placeholder}
|
|
sx={sx}
|
|
error={error}
|
|
emptyError={emptyError}
|
|
onChange={onInputChange}
|
|
onKeyDown={onKeyDown}
|
|
onBlur={onInputBlur}
|
|
value={value}
|
|
/>
|
|
);
|
|
}
|