Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Cannot restrict user input to letters only

Tags:

reactjs

I'm trying to restrict user input to letters only but for some reason it's not working. I'm very new to ReactJS so maybe my problem lies here somewhere. This is what I've got so far:

<input type="text" pattern="[a-zA-Z]*" placeholder="Add Skill" onChange={this.updateField} />

type="text" and pattern seem not to work in this case.

Thanks in advance!

like image 302
Anna Stierlitz Avatar asked Oct 17 '18 02:10

Anna Stierlitz


People also ask

How do you restrict text input in react JS?

Approach 1: Using maxLength: We will use maxLength attribute for our input. It is the same as the maxlength attribute used for HTML. It restricts the user to enter characters till it reaches the maxLength limit that we have set.

How do you restrict the input field alphabets?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I limit a character input in react?

Use the maxLength prop to set a character limit on an input field in React, e.g. <input maxLength={5} /> . The maxLength attribute defines the maximum number of characters the user can enter into an input field or a textarea element. Copied!

How do you restrict negative values in input type numbers in react?

You can add an onKeyPress listener to the input element and that will be triggered before the onChange and call a function that will prevent default behaviour when the minus button is pressed.


1 Answers

The pattern attribute is used to check against the input value when it is submitting.

Ref: https://www.w3schools.com/tags/att_input_pattern.asp


To restrict users to input only letters, you can use the onKeyPress

<input
    type="text"
    onKeyPress={event => (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122)}
    placeholder="Add Skill"
    onChange={this.updateField}
/>

This is the ASCII table: http://www.asciitable.com/


UPDATE

Codepen: https://codepen.io/jeemok/pen/rqJaog

like image 52
Jee Mok Avatar answered Oct 03 '22 22:10

Jee Mok