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