user8608046
user8608046

Reputation:

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.

Upvotes: 5

Views: 43974

Answers (8)

Saleh Alikhani
Saleh Alikhani

Reputation: 106

You can use preventDefault function of the onKeyDown event of input element if you know a character is not in english. How do you know it's not english? You can use my trick without using regular expressions: in such events, event variable is of type KeyboardEventHandler.
(event: KeyboardEvent<HTMLInputElement>) => { if(event.code.toLowerCase().includes(event.key.toLowerCase())) return null event.preventDefault() /* prevent event from typing the character in input field as it is not an english character*/ }
this block of code checks if the pressed key character ("s") is included within the key code ("keyS") which is in english just be careful to check the lowercase values as it may run into some exceptions without checking that.

Upvotes: 0

Rajesh Kumar
Rajesh Kumar

Reputation: 1

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" />

Upvotes: 0

Codemaker2015
Codemaker2015

Reputation: 1

You can try to use the Regx to solve this issue. Just check the character that entered is an alphabet using regx. If not then don't update the state value.

import React from "react";

class InputValidationDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: "text",
      name: "username",
      value: ""
    };
  }
  onChange = (e) => {
    const re = /^[A-Za-z]+$/;
    if (e.target.value === "" || re.test(e.target.value))
      this.setState({ value: e.target.value });
  };

  render() {
    const { type, name, value } = this.state;
    return (
      <div>
        <input type={type} name={name} value={value} onChange={this.onChange} />
      </div>
    );
  }
}
export default InputValidationDemo;

https://codesandbox.io/s/react-input-only-letters-qyf2j

The important part is the regular expression. You can change your validation type by changing the regex.

Upvotes: 4

zeel
zeel

Reputation: 1

  alphacheck(e: any) {
    const regex = /[A-Za-z]/;
    const chars = e.target.value.split('');
    const char = chars.pop();
    console.log(char);
    if (!regex.test(char)) {
      e.target.value = chars.join('');
      alert("Please enter only alphabets");
      e.preventDefault();
      return false;
     
    }
    else {
      return true;
    }
  }


<input placeholder="Full Name" formControlName="fullName"  pattern="[a-zA-Z]*"  (keypress)="alphacheck($event)"  name="fullname" value="" type="text" class="form-control">

Upvotes: 0

Tom O.
Tom O.

Reputation: 5941

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" />

Upvotes: 2

Harry Chilinguerian
Harry Chilinguerian

Reputation: 565

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

Upvotes: 3

bozdoz
bozdoz

Reputation: 12860

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

Upvotes: 17

Kevin Lewis
Kevin Lewis

Reputation: 241

You can use the pattern attribute in your input.

    <input pattern = “[A-Za-z]”>

Upvotes: 7

Related Questions