简体   繁体   English

如何防止用户在反应中输入负数?

[英]How to prevent user from entering negative number in react?

I want to restrict users from entering negative values.我想限制用户输入负值。 I am using min = "0".我正在使用 min = "0"。 With this i can restrict users from decrementing to 0, ie, users can only decrement value till 0. But they are able to type "-".有了这个,我可以限制用户递减到 0,即用户只能将值递减到 0。但是他们可以键入“-”。 How to prevent in react js.如何防止反应js。

https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />

Use some local component state to hold the input's value and use Math.max(0, value) to ensure the value prop/attribute is a non-negative value.使用一些本地组件 state 来保存输入的值并使用Math.max(0, value)来确保value prop/attribute 是非负值。 The input's value will be a string in the onChange handler so remember to coerce it back to a number value for state.输入的值将是onChange处理程序中的字符串,因此请记住将其强制转换为 state 的数字值。

 function App() { const [value, setValue] = React.useState(0); return ( <div className="App"> <label> Try entering a negative value <input type="number" min="0" step="1" className="w-100" value={value && Math.max(0, value)} onChange={e => setValue(e.target.value? Number(e.target.value): e.target.value)} /> </label> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

You can add an onKeyPress listener to the input element and that will be triggered before the onChange and call a function that will prevent default behaviour when the minus button is pressed.您可以向输入元素添加一个onKeyPress侦听器,该侦听器将在onChange之前触发,并调用 function 来阻止按下减号按钮时的默认行为。

const preventMinus = (e) => {
    if (e.code === 'Minus') {
        e.preventDefault();
    }
};

<input               
  type="number"
  min="0"
  onKeyPress={preventMinus}
/>

Note that this will still allow negative values to be pasted into the input.请注意,这仍然允许将负值粘贴到输入中。 For this, you can add an onPaste listener and check the clipboard data to see if it's negative and prevent the default behaviour.为此,您可以添加一个onPaste侦听器并检查剪贴板数据以查看它是否为负数并防止默认行为。

const preventPasteNegative = (e) => {
    const clipboardData = e.clipboardData || window.clipboardData;
    const pastedData = parseFloat(clipboardData.getData('text'));

    if (pastedData < 0) {
        e.preventDefault();
    }
};

<input               
  type="number"
  min="0"
  onPaste={preventPasteNegative}
  onKeyPress={preventMinus}
/>

You can use a regex to validate the input before setting the state of your input and sync the input value with your state value.您可以在设置输入的 state 之前使用正则表达式验证输入,并将输入值与 state 值同步。


<input
  type="number"                  
  onChange={this.handleChange}                        
  className="w-100"
  value= {this.state.inputVal}
/>

validateNumber = (value) => {
  //true for digits only.
  const regex = /^[0-9]+$/
  return regex.test(value);
}
handleChange = ({target}) => {
  const {name,value} = target;
  const {inputVal} = this.state;

  if(value === '') {
    return this.setState({inputVal:''});
  }

  if(this.validateNumber(value)) {
    this.setState({inputVal:value})
  } else {
    this.setState({inputVal:inputVal})
  }
}

You can filter out input value inside handlechange.您可以过滤掉句柄更改中的输入值。 Something like this:像这样的东西:

const App = () => {
  const [value, setValue] = useState("");

  const handleChange = (e) => {
    if (!isNaN(e.target.value)) {
      setValue(e.target.value);
    }
  };
  return (
    <div className="App">
      <input
        type="text"
        value={value}
        onChange={handleChange}
        className="w-100"
      />
    </div>
  );
};

Here is the demo: https://codesandbox.io/s/react-input-example-forked-kr2xc?file=/src/index.js这是演示: https://codesandbox.io/s/react-input-example-forked-kr2xc?file=/src/index.js

Handling Empty Input & Negative Numbers处理空输入和负数

// Converting App into Class-Component
class App extends React.Component {
  // Set State
  constructor(props) {
    super(props);
    this.state = {
      number: ""
    };
  }

  render() {
    return (
      <div className="App">
        <input
          type="number"
          min="0"
          step="1"
          onChange={(e) => {
            let val = parseInt(e.target.value, 10);
            if (isNaN(val)) {
              this.setState({ number: "" });
            } else {
              // is A Number
              val = val >= 0 ? val : 0;
              this.setState({ number: val });
            }
          }}
          className="w-100"
          // Assign State
          value={this.state.number}
        />
      </div>
    );
  }
}

Other solutions weren't working for me (I could input negative number from scrolling mouse wheel or trackpad), so I made a kind of hardcoded method:其他解决方案对我不起作用(我可以从滚动鼠标滚轮或触控板输入负数),所以我做了一种硬编码方法:

onChange={function (event) {
  if (value > 0 || event.target.valueAsNumber >= 0) {
    setValue(event.target.valueAsNumber);
  }
}}
<input type="number" onKeyDown={preventNegativeValues}/>

//function export //函数导出

export const preventNegativeValues = (e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()

I prefer this answer as it has alot of functionality in one.我更喜欢这个答案,因为它集多种功能于一身。
Use Math.sign() it has the following possible results:使用Math.sign()它有以下可能的结果:
it returns 1 if the argument is positive.如果参数为正,则返回 1。
it returns -1 if the argument is negative如果参数为负,则返回 -1
it returns 0 if the argument is 0如果参数为 0,则返回 0
it returns -0 if the argument is -0如果参数为 -0,则返回 -0
in all other cases it returns NaN (not a number)在所有其他情况下,它返回 NaN(不是数字)
example例子
if(Math.sign(somevalue).=1){ console.log("please provide a valid number" } } if(Math.sign(somevalue).=1){ console.log("please provide a valid number" } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止用户在Vue 3数字输入中输入低于1的值 - How to prevent user from entering value below 1 in Vue 3 number input 防止用户在数字类型的输入元素中输入负数 - Preventing user from entering negative numbers in input elements with number type 在 cellEditable 材质表上,如何限制用户输入负数? - On an cellEditable material-table, how to restrict the user from entering negative number? javascript:如何防止用户在文本框中输入=? - javascript : How to prevent user from entering = in textbox? 如何防止用户输入小数? - How to prevent user from entering decimals? 阻止用户输入一个浮点数,该数字大于3位小数 - Prevent user from entering a float number, greater than 3 decimals 如何防止用户在不更改代码的情况下将数据输入表单? - How to prevent user from entering data into a form without changing the code? 如何防止用户在 ReactJS 的输入表单字段中输入空格? - How to prevent user from entering spaces in an input form field in ReactJS? 如何阻止用户使用javascript输入“&gt;”和“&lt;”字符? - How do I prevent the user from entering '>' and '<' characters with javascript? 如何防止用户在输入字段中输入字符“`”? - How to prevent the user from entering the character "`" in the Input field?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM