8

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:

return (
    <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!

asportnoy
  • 2,218
  • 2
  • 17
  • 31
Anna Stierlitz
  • 119
  • 1
  • 2
  • 6

2 Answers2

9

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 1

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

UPDATE 2: charCode is deprecated

key return the typed character, so we may check if converting the key to number returns NaN:

onKeyPress(event) {
  return (isNaN(Number(event.key));
}
Jee Mok
  • 6,157
  • 8
  • 47
  • 80
0

You can use Yup/Joi or other validator if you are going to use them several times and have more things to validate for that task as the regex are already there and tested. https://www.npmjs.com/package/yup https://www.npmjs.com/package/joi