2023-04-15 19:37:50 +02:00
|
|
|
import React, {useState} from 'react';
|
|
|
|
|
|
|
|
export default function ValidatingInputNumberField({
|
|
|
|
id,
|
|
|
|
label,
|
2023-04-16 01:01:23 +02:00
|
|
|
value = 0,
|
2023-04-15 19:37:50 +02:00
|
|
|
constraints = {},
|
|
|
|
validatorFn = (value) => {
|
|
|
|
return {valid: true, value};
|
|
|
|
},
|
|
|
|
disabled = false,
|
|
|
|
onChange = _ => {
|
|
|
|
}
|
|
|
|
}) {
|
|
|
|
const [error, setError] = useState(null);
|
|
|
|
|
|
|
|
const handleValueChange = (e) => {
|
|
|
|
const value = e.target.value;
|
|
|
|
const validation = validatorFn(value);
|
|
|
|
if (!validation.valid) {
|
|
|
|
setError(validation.message);
|
|
|
|
} else {
|
|
|
|
setError(null);
|
|
|
|
}
|
2023-04-16 01:01:23 +02:00
|
|
|
onChange(validation.value);
|
2023-04-15 19:37:50 +02:00
|
|
|
};
|
|
|
|
return (
|
2023-04-16 02:34:11 +02:00
|
|
|
<>
|
2023-04-15 19:37:50 +02:00
|
|
|
<label htmlFor={id}>{label}: </label>
|
|
|
|
<input id={id}
|
|
|
|
type={"number"}
|
|
|
|
onChange={handleValueChange}
|
|
|
|
value={value || ""}
|
|
|
|
min={constraints.min || null}
|
|
|
|
max={constraints.max || null}
|
|
|
|
disabled={disabled}
|
|
|
|
/>
|
2023-04-16 02:34:11 +02:00
|
|
|
{!!error && <span>{error}</span>}
|
|
|
|
</>
|
2023-04-15 19:37:50 +02:00
|
|
|
);
|
|
|
|
}
|