Check if input is number or letter javascript

前端 未结 12 1300
遇见更好的自我
遇见更好的自我 2020-11-29 01:03

I\'m using forms in HTML and javascript. I would like an alert to pop up only if the user inputs a LETTER and clicks submit.

So I have

相关标签:
12条回答
  • 2020-11-29 01:21

    I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:

        const regex = new RegExp(/[^0-9]/, 'g');
        const x = document.forms["myForm"]["age"].value;
    
        if (x.match(regex)) {
           alert("Must be a valid number");
           return;
        }
       
    
    0 讨论(0)
  • 2020-11-29 01:24

    Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.

    function checkInp()
    {
        var x=document.forms["myForm"]["age"].value;
        var regex=/^[a-zA-Z]+$/;
        if (!x.match(regex))
        {
            alert("Must input string");
            return false;
        }
    }
    

    Even better would be to deny anything but numbers:

    function checkInp()
    {
        var x=document.forms["myForm"]["age"].value;
        var regex=/^[0-9]+$/;
        if (x.match(regex))
        {
            alert("Must input numbers");
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 01:26

    The best and modern way is typeof (variable) if you care about real number not number from string. For example:

    var a = 1;
    var b = '1';
    
    typeof a: // Output: "number"
    typeof b: // Output: "string
    
    0 讨论(0)
  • 2020-11-29 01:29

    you can use isNaN(). it returns true when data is not number.

    var data = 'hello there';
    if(isNaN(data)){
      alert("it is not number");
    }else {
      alert("its a valid number");
    }
    
    0 讨论(0)
  • 2020-11-29 01:31

    Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

    function checkInp()
    {
        var x = document.forms["myForm"]["age"].value;
        if ((x%1) != 0) 
        {
            alert("Must input numbers");
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 01:33

    Thanks, I used @str8up7od answer to create a function today which also checks if the input is empty:

        function is_number(input) {
            if(input === '')
                return false;
            let regex = new RegExp(/[^0-9]/, 'g');
            return (input.match(regex) === null);
        }
    
    0 讨论(0)
提交回复
热议问题