ReactJs prevent e and dot in an input type number

前端 未结 6 1550
轮回少年
轮回少年 2020-12-18 01:52

I would like to prevent e and . to be type in an . Without jQuery or using step attribute.

6条回答
  •  长情又很酷
    2020-12-18 02:07

    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;
    

提交回复
热议问题