Check if input is number or letter javascript

前端 未结 12 1304
遇见更好的自我
遇见更好的自我 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: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;
        }
    }
    

提交回复
热议问题