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!
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.
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.
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!
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.
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/
Codepen: https://codepen.io/jeemok/pen/rqJaog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With