How to allow only English letters in input fields?

前端 未结 4 1644
无人及你
无人及你 2021-01-14 17:30

So, this is my input field:


How can I allow only English letters?

This is the RegEx

相关标签:
4条回答
  • 2021-01-14 17:33

    You could use /[A-Za-z]/ regular expression and an input event handler which is fired every time the value of the element changes. Something like below:

    const regex = /[A-Za-z]/;
    function validate(e) {
      const chars = e.target.value.split('');
      const char = chars.pop();
      if (!regex.test(char)) {
        e.target.value = chars.join('');
        console.log(`${char} is not a valid character.`);
      }
    }
    document.querySelector('#myInput').addEventListener('input', validate);
    <label for="myInput">Type some text:</label>
    <input id="myInput" type="text" />

    0 讨论(0)
  • 2021-01-14 17:34

    You can use the pattern attribute in your input.

        <input pattern = “[A-Za-z]”>
    
    0 讨论(0)
  • 2021-01-14 17:41

    This should do the trick, all characters except ascii 0-127 which are English characters should be excluded, o through 127 also gives you space, +, -, / and punctuation which is useful, if you want only letters then [^A-z] should do the trick, if you need non-space characters then [^A-z\s] should work:

    document.getElementById('english').addEventListener('input', function(){
      this.value = this.value.replace(/[^\x00-\x7F]+/ig, '');
    });
    

    React Way:

    class InputEnglish extends React.Component {
      constructor(){
        super();
        this.state = {value: ''};
        this.onChange = this.onChange.bind(this);
      }
      onChange(e) {
        let val = e.target.value.replace(/[^\x00-\x7F]/ig, '');
        this.setState(state => ({ value: val }));
      }
      render() {
        return (<input 
            value={this.state.value}
            onChange={this.onChange}
        />);
      }
    }
    

    https://codepen.io/anon/pen/QVMgrd

    0 讨论(0)
  • 2021-01-14 17:49

    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 ''

    0 讨论(0)
提交回复
热议问题