javascripthtmlreactjsformsvalidation

How to allow only English letters in input fields?


So, this is my input field:

<input type={type} name={name} />

How can I allow only English letters?

This is the RegEx, I believe I should use: /[A-Za-z]/ig

https://regex101.com/r/upWFNy/1

I am assuming that onChange() event should be used for this with the combination of setState() and event.target.value.

Thanks.

PS. I need to have this WHILE typing.


Solution

  • I would try this onChange function:

    onChange={(e) => {
      let value = e.target.value
    
      value = value.replace(/[^A-Za-z]/ig, '')
    
      this.setState({
        value,
      })
    }}
    

    See the codepen: https://codepen.io/bozdoz/pen/vzJgQB

    The idea is to reverse your regex matcher with ^ and replace all non-A-z characters with ''