Best practice of html5 input for limited length

What you need is ,

  • Only numbers can be input
  • The length of input is limited to N, say 2
  • On mobile devices, a number pad will be shown

And the way to do it is:

<input type="number" pattern="[0-9]*" oninput="this.value=this.value.slice(0,2)"/>

If you are using material-ui, it will be

<TextField
    inputProps={{
        type: "number",
        pattern: "[0-9]*" 
    }}

    onInput={(e: any)=>{
        e.target.value = e.target.value.slice(0,2)
    }}
/>

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.