Javascript - validation, numbers only

前端 未结 14 1685
感动是毒
感动是毒 2020-12-08 09:52

I\'m trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number,

相关标签:
14条回答
  • 2020-12-08 10:18

    Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.

    Edit:

    RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.

    Simply omit the negating ! and use if(/\D/.test(z)).

    0 讨论(0)
  • 2020-12-08 10:23

    Using the form you already have:

    var input = document.querySelector('form[name=myForm] #username');
    
    input.onkeyup = function() {
        var patterns = /[^0-9]/g;
        var caretPos = this.selectionStart;
    
        this.value = input.value.replace(patterns, '');
        this.setSelectionRange(caretPos, caretPos);
    }
    

    This will delete all non-digits after the key is released.

    0 讨论(0)
  • 2020-12-08 10:24

    Late answer,but may be this will help someone

    function isNumber(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    

    Use will be like

    nn=document.forms["myForm"]["num"].value;
    
    ans=isNumber(nn);
    
    if(ans)
    {
        //only numbers
    }
    

    This ans was found from here with huge vote

    Validate numbers in JavaScript - IsNumeric()

    0 讨论(0)
  • 2020-12-08 10:24

    function validateNumber(e) {
                const pattern = /^[0-9]$/;
    
                return pattern.test(e.key )
            }
     
     <input name="username" id="username" onkeypress="return validateNumber(event)">

    This approach doesn't lock numlock numbers, arrows, home, end buttons and etc

    0 讨论(0)
  • 2020-12-08 10:25

    Regular expressions are great, but why not just make sure it's a number before trying to do something with it?

    function addemup() {
    var n1 = document.getElementById("num1");
    var n2 = document.getElementById("num2");
    sum = Number(n1.value) + Number(n2.value);
        if(Number(sum)) {
            alert(sum);
            } else {
                alert("Numbers only, please!");
            };
        };
    
    0 讨论(0)
  • 2020-12-08 10:31

    I think we do not accept long structure programming we will add everytime shot code see below answer.

    <input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

    0 讨论(0)
提交回复
热议问题