wasp
wasp

Reputation: 21

react-hook-form Limiting Length and Type using Material UI Text Field

Given the code below, I am unable to limit the number of digits a user can enter into a text field and control the type of input.

If I remove type: "number" then the input length can be controlled but letters can now be entered.

If I remove maxLength: 4 then the input length can't be controlled but letters are no longer allowed.

If I set inputProps={{ maxLength: 4, type: "number" }} as seen below, only the type: "number" input constraint is being enforced.

What can I do to fix this?

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: "25ch"
    }
  }
}));

export default function BasicTextFields() {
  const classes = useStyles();

  return (
    <form className={classes.root} noValidate autoComplete="off">
      <TextField
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        inputProps={{ maxLength: 4, type: "number" }}
      />
    </form>
  );
}

Upvotes: 2

Views: 15826

Answers (2)

tkerwood
tkerwood

Reputation: 1905

I removed the type=numeric and added some regx. Note I am using Controller not Register.

<Controller
        rules={{ required: required }}
        control={control}
        name={name}
        render={({ field }) => (
          <TextField
            {...field}
            onKeyDown={numericOnly}
            inputProps={{ inputMode: "numeric", pattern: pattern ?? "[0-9]*", maxLength:maxLength }}
          />
        )}
      />
  const numericOnly = (e) => {
    if (
      !/[0-9]/.test(e.key) &&
      e.key !== "Backspace" &&
      e.key !== "Delete" &&
      e.key !== "Enter"
    ) {
      e.preventDefault();
    }
  };

Upvotes: 0

Zachary Haber
Zachary Haber

Reputation: 11037

maxlength doesn't apply to number inputs, you need to use a combination of min and max values.

A user can still input values above the max number but the validation will show as an error. And if they use the spinners, that'll be the max value it'll go to.

label {
  display: block;
}
<label>text - maxlength=4 <input maxlength="4" /></label>

<label>number - maxlength=4 <input type="number" maxlength="4" /></label>

<label>number - max=999&amp;min=-999 <input type="number" max="999" min="-999" /></label>

Upvotes: 3

Related Questions