当前位置:网站首页>Input can only input numbers, limited input

Input can only input numbers, limited input

2022-07-06 16:14:00 Dream height 1.8 meters

string.replace(/[^\d]/g, ''), Replace non numeric characters in the string with empty characters
/[^\d]/g It's a regular expression , Match non numeric characters globally

1 onkeyup event

<html>

<head>
    <script src="https://unpkg.com/[email protected]/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>

<body>
    <div id="root"></div>
</body>
<script type="text/babel"> const e = React.createElement; const custom = () => {
       return <input placeholder=" Please enter " onKeyUp={
      e => e.target.value = e.target.value.replace(/[^\d]/g, '')} /> } const domContainer = document.querySelector('#root'); ReactDOM.render(e(custom), domContainer); </script>

</html>

 Insert picture description here
If you put onkeyup Switch to onkeydown or onkeypress, It doesn't work , although onkeyup The effect of is not very good
 Insert picture description here

2 onchange coordination value

onkeyup The essence of the event is to change when the keyboard is released input Internal value , The direct use onchange and value Not on it .

<html>

<head>
    <script src="https://unpkg.com/[email protected]/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>

<body>
    <div id="root"></div>
</body>
<script type="text/babel"> const e = React.createElement; const custom = () => {
       const [number, setNumber] = React.useState() return <input placeholder=" Please enter " value={
      number} onChange={
      e => setNumber(e.target.value.replace(/[^\d]/g, ''))} /> } const domContainer = document.querySelector('#root'); ReactDOM.render(e(custom), domContainer); </script>

</html>

You may not see it on the moving picture , Actually, I'm typing ’2’ Then press the letter key crazily
 Insert picture description here

3 Restrict input rules ( Regular expression )

You can only enter Numbers string.replace(/[\D]/g, ''))
You can only enter Numbers 、 english string.replace(/[^A-Za-z0-9]/g, ''))
You can only enter Numbers 、 english 、 Down slash string.replace(/[\W]/g, ''))
You can only enter Numbers 、 decimal point ( It's not a decimal , There can be multiple decimal points )string.replace(/[^0-9.]/g, ''))

原网站

版权声明
本文为[Dream height 1.8 meters]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060920187145.html