Home  >  Q&A  >  body text

javascript - How can I prevent input of type=number from adding plus signs, minus signs and multiple decimal points?

Thank you in advance. I wrote an Input with type = number. Due to business needs, only numbers can be entered in this Input, and the plus and minus signs cannot be entered.
Originally I wanted to judge the value in the input and manually delete the plus signs, minus signs and redundant dots, but I found that once the input value is illegal, the value of the input has been converted into an empty string ''. In this way I cannot get the value in the input.
I’ve been thinking about it for a long time but don’t know the solution. Please help me, thank you~
By the way, I wrote the page in vue~~~

给我你的怀抱给我你的怀抱2713 days ago1362

reply all(6)I'll reply

  • 为情所困

    为情所困2017-05-16 13:39:46

    Use regular expression to match '^[-]?[0-9]*.?[0-9]+(eE?[0-9]+)?$'

    <input type="text" />

    You can use this method to monitor the changes in the input value. If you find that the verification fails, you will be prompted.

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome</title>
    </head>
    <body>
    <form>
        <input id="inputNumber" type="text" name="test" onblur="checkNumber()">
    </form>
    
    <script type="text/javascript">
     function checkNumber(){
        var inputNumber = document.getElementById('inputNumber').value;
        if(!/^[-]?[0-9]*\.?[0-9]+(eE?[0-9]+)?$/.test(inputNumber)){
            alert('Please input a valid number!');
            return false;
        }
    }
    </script>
    </body>
    </html>

    reply
    0
  • 某草草

    某草草2017-05-16 13:39:46

    Post your js and take a look

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 13:39:46

    onkeyup="this.value=this.value.replace(/D/g,'')" onafterpaste="this.value=this.value.replace(/D/g,'')"

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:39:46

    type=number should not be able to directly restrict users from entering positive and negative signs, e, and multiple decimal points.
    It still needs to be judged by the value of the input.
    As for the problem that the input value is illegal and the input value is converted into an empty string,
    You can change the input type to text, and then use regular expressions and replace to remove non-digits and multiple decimal points.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:39:46

    Then you can use v-model to bind a value, and then monitor the value through watch. But when you find an illegal value, just delete the illegal string

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:39:46

    <input type="tel" />

    reply
    0
  • Cancelreply