Check if input is number or letter javascript

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

提交回复
热议问题