Spaces:
Sleeping
Sleeping
File size: 1,714 Bytes
79278ec |
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 |
import { useEffect } from "react";
import { InputProps } from "./Input.interface";
import "./Input.scss";
const Input = ({
name,
placeholder,
rules,
value = "",
onSetValue,
label,
error,
onSetError,
extra,
...props
}: InputProps) => {
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (props.type == "number") {
const { value, max, min } = event.target;
if (Number(value) > Number(max)) {
onSetValue(max);
} else if (Number(value) > Number(min)) {
onSetValue(value);
} else {
onSetValue("");
}
} else {
onSetValue(event.target.value);
}
};
const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (props.type === "number") {
if (!/[0-9]/.test(event.key) && event.key !== "Backspace") {
event.preventDefault();
}
}
};
useEffect(() => {
if (value.length > 0) {
rules?.some((rule) => {
if (!rule.rule(value)) {
// console.log(value);
onSetError?.(rule.errorMessage);
return true;
}
// console.log(value);
onSetError?.(null);
return false;
});
}
}, [onSetError, rules, value]);
return (
<div className={"input_container"}>
{label}
<div className="with_icon_container">
<input
className={"input"}
name={name}
placeholder={placeholder}
value={value}
onChange={handleChange}
onKeyPress={handleKeyPress}
{...props}
/>
{extra}
</div>
{error && <div className={"error"}>{error}</div>}
</div>
);
};
export default Input;
|