简体   繁体   English

JavaScript实时验证

[英]JavaScript real-time validation

I have a website for mobile subscribers, and i want the field where they enter their phone numbers to accept only "numbers" and the numbers should be only 7 digits, no more, no less. 我有一个面向移动订户的网站,我希望他们在其中输入电话号码的字段仅接受“数字”,并且该数字应仅为7位数字,且不能多于或等于。 So if they try to input non-integer sign it'll be auto removed/will not even show up... How to achieve that? 因此,如果他们尝试输入非整数符号,它将被自动删除/甚至不会显示...如何实现?

Well, for limiting the length of the input, use the maxlength attribute to the input element. 好吧,为了限制输入的长度,请对input元素使用maxlength属性。

To only allow numeric characters, bind a JavaScript event handler to the keypress event, and preventDefault from the event object to drop the key if it isn't a number. 要仅允许数字字符,请将JavaScript事件处理程序绑定到keypress事件,并防止来自事件对象的preventDefault丢弃键(如果它不是数字)。

Edit: 编辑:

Do some testing to make sure other commonly-used keycodes are allowed in addition to number character keys, such as arrow keys, delete and backspace. 进行一些测试,以确保除数字字符键(例如箭头键,删除键和退格键)外,还允许使用其他常用的键码。 If the user can't do these, it'll certainly be a problem. 如果用户不能执行这些操作,那肯定是一个问题。

There are other ways to approach this. 还有其他方法可以解决此问题。 You could, for example, avoid the trouble of allowing other special keys, by filtering and deleting non-numeric characters entered each time a key is pressed, which should be invisible and instant seeing as the maximum number of characters is 7. 例如,您可以通过过滤和删除每次按下的键输入的非数字字符来避免允许其他特殊键的麻烦,因为每次最多只能输入7个字符,因此这些键应该是不可见的并且可以立即看到。

Edit 2: 编辑2:

If this seems reasonable for you, HTML5 introduces a number of native form validation features that may help, and are supported by fairly recent versions (and newer) of most browsers. 如果您觉得这很合理,HTML5引入了许多本机表单验证功能,这些功能可能会有所帮助,并且大多数浏览器的最新版本(和较新版本)都支持这些功能。 This is great to also cover those who don't have JavaScript enabled (but, remember, always do server-side validation as well). 这对于覆盖未启用JavaScript的用户也非常有用(但请记住,也请务必进行服务器端验证)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM