'Reactjs TextField helperText

how can I synchronize error validation with the character limit without affecting its functions, please see this https://codesandbox.io/s/nostalgic-mestorf-47jsvk?file=/src/App.js

  const [formError, setFormError] = useState(false);
  const CHARACTER_LIMIT = 1000;
  const [getString, setString]= useState({
    value: "",
    length: 0
  })


const onHandleChangeInput = (field, value) => {
  setString({value: value, length: value.length})
}
  const onHandleInputValidation = (field, value) => {
    try {
      Joi.assert(value, _.get(VALIDATION_SCHEMA, field));
      setFormError(_.omit(formError, field));
      return { error: false, valid: true };
    } catch (err) {
      return { error: err.message, valid: false };
    }
  };
    <TextField
      label="Name"
      inputProps={{
        maxlength: CHARACTER_LIMIT
      }}
      values={getString.name}
      onChange={(value) => onHandleChangeInput('name', value)}
      error={Boolean(formError.name)}
      helperText={{formError.name}, `${getString.length}/${CHARACTER_LIMIT}`}
    />

what i want is just like this

enter image description here



Solution 1:[1]

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

Solution 2:[2]

You cannot exceed the charachter limit as long as you have not removed inputProps={{ maxLength: CHARACTER_LIMIT }}, after that you could use FormHelperText component and pass two messages as follows:

<FormHelperText
  error={Boolean(formError.name)}
  sx={{
    display: 'flex',
    justifyContent: 'space-between',
    padding: '0 10px'
  }}
>
  <span>{formError.name}</span>
  <span>{`${getString.length}/${CHARACTER_LIMIT}`</span>
</FormHelperText>

Edit mui FormHelperText two messages

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sakshi Mahajan
Solution 2 Fraction