how can I synchronize error validation with the character limit without affecting its functions, please see this
CodePudding user response:
Your onChange handler gets the event
. You need to get the value
out of it.
- Update the
onHandleChangeInput
like below.
const onHandleChangeInput = (field, event) => {
const { value } = event.target;
setString({ value: value, length: value.length });
onHandleInputValidation(field, value);
};
- name the parameter as
event
instead ofvalue
to be clear.
onChange={(event) => onHandleChangeInput("name", event)}
- Use a ternary to show
error message
orhelperText
.
helperText={
Boolean(formError.name)
? formError.name
: `${getString.length}/${CHARACTER_LIMIT}`
}
CodePudding user response:
import React, { useState } from "react";
import { TextField } from "@mui/material";
import "./styles.css";
export default function App() {
const CHARACTER_LIMIT = 1000;
const [getString, setString] = useState({
value: "",
length: 0
});
const onHandleChangeInput = (field, value) => {
const { value: inputValue } = value.target;
setString({ value: inputValue, length: inputValue.length });
};
return (
<TextField
label="Name"
inputProps={{
maxLength: CHARACTER_LIMIT
}}
values={getString.value}
onChange={(e) => onHandleChangeInput("name", e)}
error={Boolean(getString.length === CHARACTER_LIMIT)}
helperText={`${getString.length}/${CHARACTER_LIMIT}`}
/>
);
}
you are not using value from onChange as you were sending event then I extracted that value for you. Take a look
CodePudding user response:
You cannot exceed the charachter limit as long as you have not removed inputProps={{ maxLength: CHARACTER_LIMIT }}
, after that you could use