我们如何获得一个JavaScript程序来防止数字输入? [英] How can we get a javascript program to prevent numeric input?

查看:23
本文介绍了我们如何获得一个JavaScript程序来防止数字输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,如果输入数字,则必须抛出错误

I mean if number is entered, it must throw an error

推荐答案

如果要排除数字,只需用regEx替换它们以防止输入.您可以告诉用户也不允许他们输入数字.

If you want to exclude numbers just prevent them from being entered by replacing them with regEx. You can tell the user that they're not allowed to enter numbers as well..

//collect the string
var userStr = getTheString();//whatever the source of the string is... probably called onKeyUp
if(userStr.match(/\d/)){
   userStr = userStr.replace(/\d+/g,"");//[edited to include all digits]
   alert("no numbers please");
}

这听起来像是一项家庭作业,因此要明确地说,正则表达式是执行各种字符串操作和验证的一种非常有效的方法.在上面的示例中,我正在测试(使用match)以查看字符串中是否存在任何数字.我建议在用户从键盘上抬起手指时都运行此命令,这样可以确保防止未经授权的输入.replace()方法查找字符串中的所有数字(\ d +),并将其替换为第二个参数,它只是一个空字符串.显然,您可以使用循环和您自己的字符串方法,以更加复杂的方式完成所有这些工作,逐个字母地处理字符串,然后提取数字char,如果您的老师希望看到您在没有regEx的情况下解决这个问题(对于必须学习算法思维的初学者来说,这是完全合理的),那么您应该这样说,我们很乐意以丑陋"的方式帮助您做到这一点.

[edit] This sounds like a homework assignment, so to be clear, regular expressions are a really powerful way to do all sorts of string manipulation and validation. In the above example I am testing (using match) to see if any digits exist in the string. I recommend running this whenever the user lifts their finger from the keyboard, that way you are guaranteed to prevent unauthorized input. The replace() method seeks out any and all digits (\d+) in the string and replaces them with the second parameter, which is just an empty string. You can obviously do this all in much more convoluted ways, with loops and your own string methods, going through the string letter by letter and then extracting the number chars, and if your teacher wishes to see you figure this out without the comforts of regEx (which is totally reasonable, for a beginner programmer who has to learn algorithmic thinking) then you should say that, and we'll gladly help you do it the "ugly" way.

干杯.

这篇关于我们如何获得一个JavaScript程序来防止数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆