I would like to prevent e and . to be type in an . Without jQuery or using step attribute.
Here is a pretty robust solution to prevent the characters that are not numbers ("e", ".", "+" & "-") !
import React, { Component } from "react";
class MyComponent extends React.Component {
state = { numInput: "" };
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
formatInput = (e) => {
// Prevent characters that are not numbers ("e", ".", "+" & "-") ✨
let checkIfNum;
if (e.key !== undefined) {
// Check if it's a "e", ".", "+" or "-"
checkIfNum = e.key === "e" || e.key === "." || e.key === "+" || e.key === "-" ;
}
else if (e.keyCode !== undefined) {
// Check if it's a "e" (69), "." (190), "+" (187) or "-" (189)
checkIfNum = e.keyCode === 69 || e.keyCode === 190 || e.keyCode === 187 || e.keyCode === 189;
}
return checkIfNum && e.preventDefault();
}
render(){
return (
}
}
export default MyComponent;