Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

maxLength for text-input box #1578

Closed
xuansehyun opened this issue Sep 2, 2015 · 17 comments
Closed

maxLength for text-input box #1578

xuansehyun opened this issue Sep 2, 2015 · 17 comments

Comments

@xuansehyun
Copy link

@xuansehyun xuansehyun commented Sep 2, 2015

Hi I was wondering if there is a property to set the max length of the text-input so that when the user enters a certain amount of letters they will not be able to enter any more?
thanks a lot!

@shaurya947
Copy link
Contributor

@shaurya947 shaurya947 commented Sep 21, 2015

Hey @xuansehyun , you should just be able to set the attribute maxLength on your TextField element like so:

<TextField
    style={styles.textfield}
    hintText="Hint Text (MultiLine)"
    multiLine={true} 
    maxLength="2" />

Let me know if that doesn't work.

@otroboe
Copy link

@otroboe otroboe commented Nov 18, 2015

It works for me, you can close this I think :)

@oliviertassinari
Copy link
Member

@oliviertassinari oliviertassinari commented Nov 18, 2015

@otroboe I agree.

@mrjosshi
Copy link

@mrjosshi mrjosshi commented Sep 25, 2017

how to can i add validation error if there is min length is less then defined minLength

@dkaplan-pivotal
Copy link

@dkaplan-pivotal dkaplan-pivotal commented Mar 27, 2018

<div class="MuiFormControl-root-100" maxlength="2" style="display: block;">
  <div class="MuiInput-root-104 SendAnnouncementFormComponent-textFieldTextRoot-90 MuiInput-formControl-105 MuiInput-multiline-111">
    <textarea class="MuiInput-input-113 SendAnnouncementFormComponent-textFieldTextInput-92 MuiInput-inputMultiline-117" id="announcementText" name="text" placeholder="Update Text" type="text" rows="10" aria-required="false" aria-invalid="false"></textarea>
  </div>
</div>

I tried this and it didn't work. The maxLength ended up on a div, not the textarea. Here's my code that generated the above HTML.

<TextField
              InputProps={{
                id: 'announcementText',
                disableUnderline: true,
                multiline: true,
                rows: 10,
                classes: {
                  root: textFieldTextRoot,
                  input: textFieldTextInput,
                },
              }}
              maxLength="2"
              name="text"
              type="text"
              value={this.state.text}
              onChange={this.handleInputChange}
              placeholder="Update Text"
              style={{ display: 'block' }}
            />

"material-ui": "1.0.0-beta.30",

Update: I found out I can get this working by using inputProps={{maxLength: 2}}. The casing is important. It does not work on InputProps

There is no documentation about maxLength directly on a TextField.

@bmoeskau
Copy link

@bmoeskau bmoeskau commented Apr 8, 2018

I am also having trouble getting this working with the betas, and it definitely seems like it should be a property directly on the component API.

@arminydy
Copy link
Contributor

@arminydy arminydy commented Apr 14, 2018

@JarLowrey answered it here: #5309 (comment)

For the reference I mention it here too. To limit the number of input length 'e.g. 10' in material-ui@v1.0.0-beta.42, try this code:

<TextField
  inputProps={{
    maxLength: 10,
  }}
/>
@kenecaswell
Copy link

@kenecaswell kenecaswell commented Sep 11, 2018

Note that InputProps and inputProps are two different properties of TextField. This fact wasted a few hours of my life.

<TextField
  InputProps={{ 
    disableUnderline: true
  }}
  inputProps={{
    maxLength: 10
  }}
/>
@skirankumar7
Copy link

@skirankumar7 skirankumar7 commented Dec 10, 2018

Note that InputProps and inputProps are two different properties of TextField. This fact wasted a few hours of my life.

<TextField
  InputProps={{ 
    disableUnderline: true
  }}
  inputProps={{
    maxLength: 10
  }}
/>

In the same way min length property also works right?

@fijijavis
Copy link

@fijijavis fijijavis commented Dec 20, 2018

@kenecaswell thanks for the posts, i just spent an hour trying to figure out what i was doing wrong.

@invision-008
Copy link

@invision-008 invision-008 commented Mar 15, 2019

@kenecaswell You just saved a life 👍 Thanks bro !!

@rahulsharmaaa
Copy link

@rahulsharmaaa rahulsharmaaa commented Mar 25, 2019

If there is type='number', maxLength won't work
<TextField
type='number'
inputProps={{
maxLength: 10,
}}
/>
It should be:
<TextField
inputProps={{
maxLength: 10,
}}
/>

@Puneet1796
Copy link

@Puneet1796 Puneet1796 commented Sep 12, 2019

A better solution without any attribute (in case they does not work).
In your TextField's onChange(), update your state only if the length of the value is equal to <YOUR_MAX_LENGTH>.

onChange = (event) => {
      // Check if the textfield's that
      // you're getting has a name attribute which has a value of <YOUR_UNIQUE_IDENTIFIER>

      if (event.target.name === <YOUR_UNIQUE_IDENTIFIER>
            && event.target.value !== <YOUR_MAX_LENGTH>) {
            // Update your state here
      }
}

@geekvikas
Copy link

@geekvikas geekvikas commented Sep 17, 2019

A better solution without any attribute (in case they does not work).
In your TextField's onChange(), update your state only if the length of the value is equal to <YOUR_MAX_LENGTH>.

onChange = (event) => {
      // Check if the textfield's that
      // you're getting has a name attribute which has a value of <YOUR_UNIQUE_IDENTIFIER>

      if (event.target.name === <YOUR_UNIQUE_IDENTIFIER>
            && event.target.value !== <YOUR_MAX_LENGTH>) {
            // Update your state here
      }
}

OnChange is never a better solution as it will still fire the event even after the limit has reached, it might seem like nothing with modern CPU but we should design our systems to enforce restrictions at the HTML level if we can. maxLength is HTML attribute and cross browser compatible even without JavaScript

@luansantosti
Copy link

@luansantosti luansantosti commented Mar 6, 2020

inputProps={{ maxLength: 365 }} works for me.

@michaelscraft
Copy link

@michaelscraft michaelscraft commented May 26, 2020

In case you are using formik-material-ui the way to go will be:

<Field
  component={TextField}
  InputProps={{
      inputProps: { maxLength: 5 },
  }}
/>
@Tokenyet
Copy link
Contributor

@Tokenyet Tokenyet commented Oct 28, 2020

I want to use type='number', so the only solution for me is to use substring at setState part.

Example:

  const [deposit, setDeposit] = React.useState<number | null>(null);
  const disabled = deposit == null || deposit < 0 || deposit === 0;

  return (
      <TextField
        variant='outlined'
        color='primary'
        fullWidth
        type='number'
        value={deposit}
        onChange={(e) => setDeposit(Number(e.target.value.substring(0, 6)))} // This line to limit the length!
        label='Deposit'
        InputProps={{
          endAdornment: (
            <InputAdornment position='end'>
              <Button
                variant='text'
                disabled={disabled}
                color={'primary'}
                onClick={(_) => onSend(deposit!)}>
                <Typography color='primary'>{'Submit'}</Typography>
              </Button>
            </InputAdornment>
          )
        }}
      />
mnajdova pushed a commit to mnajdova/material-ui that referenced this issue Nov 10, 2020
Bumps [acorn](https://github.com/acornjs/acorn) from 5.7.3 to 5.7.4. **This update includes a security fix.**
- [Release notes](https://github.com/acornjs/acorn/releases)
- [Commits](acornjs/acorn@5.7.3...5.7.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet