Validate and limit the text in input fields

This commit is contained in:
powermaker450 2024-09-09 13:47:48 -04:00
parent 6d05f9e81f
commit 2cedf0716d
2 changed files with 32 additions and 3 deletions

View file

@ -17,15 +17,24 @@ function App() {
{
name: "Name",
dynamicState: useState(""),
validateInput: ({ length }) => length >= 2 && length <= 30,
errorText: "Name must be at least 2 characters",
maxLength: 30
},
{
name: "Title",
dynamicState: useState(""),
validateInput: ({ length }) => !length || length <= 50,
errorText: "Title must be less than 50 characters",
maxLength: 50
},
{
name: "Content",
dynamicState: useState(""),
expandable: true,
validateInput: ({ length }) => !length || length <= 2000,
errorText: "Content must be less than 2000 characters",
maxLength: 2000
},
];

View file

@ -6,7 +6,9 @@ export interface ReviewFieldProps {
dynamicState: [string, React.Dispatch<React.SetStateAction<string>>];
expandable?: boolean;
variant?: "outlined" | "filled" | "standard";
help?: string;
validateInput: (value: string) => boolean;
maxLength: number;
errorText: string;
}
interface ReviewFieldOpts {
@ -18,6 +20,19 @@ const ReviewField = ({ fields }: ReviewFieldOpts) => {
<Box component="form" noValidate autoComplete="off">
<Stack spacing={1}>
{fields.map((field) => {
const [errorText, setErrorText] = useState("");
const [error, setError] = useState(false);
const showTheError = () => {
setErrorText(field.errorText);
setError(true);
}
const hideTheError = () => {
setErrorText("");
setError(false);
}
return (
<TextField
id={field.name}
@ -26,10 +41,15 @@ const ReviewField = ({ fields }: ReviewFieldOpts) => {
value={field.dynamicState[0]}
multiline={field.expandable ?? false}
onChange={({ target }) => {
field.dynamicState[1](target.value);
field.dynamicState[1](target.value.length <= field.maxLength ? target.value : field.dynamicState[0]);
field.validateInput(field.dynamicState[0])
? hideTheError()
: showTheError();
}}
variant={field.variant ?? "outlined"}
helperText={field.help}
error={error}
helperText={errorText}
autoComplete="off"
/>
);