简体   繁体   English

使用JavaScript验证用户输入

[英]Validating user input with JavaScript

I need to make it so a user can ONLY type a-z0-9 into my input box. 我需要这样做,以便用户只能在我的输入框中键入a-z0-9。 How can I make it so the user simply cannot type other characters? 我该如何做,以便用户根本无法键入其他字符? If this isn't possible, how can I simply check the input with regex? 如果这不可能,我该如何简单地使用正则表达式检查输入?

Thanks! 谢谢!

If you use jQuery, there is a format plugin that does exactly what you need. 如果您使用jQuery,则可以使用完全符合您需要的格式插件 Other than that, you can use onkeyup/onkeyup to call function which will validate input against regex pattern. 除此之外,您可以使用onkeyup / onkeyup调用函数,该函数将根据正则表达式模式验证输入。

Another notable solution is this alphanumeric plugin for jquery: http://itgroup.com.ph/alphanumeric/ 另一个值得注意的解决方案是这个用于jQuery的字母数字插件: http : //itgroup.com.ph/alphanumeric/

Simple as $('#textField').alphanumeric(); 简单为$('#textField').alphanumeric();

You can use the onKeyDown event. 您可以使用onKeyDown事件。 If you return false from your event handler, no key press event is fired and the key is "eaten". 如果从事件处理程序返回false,则不会触发任何按键事件,并且按键会被“吃掉”。

Here are the docs from Sun: http://docs.sun.com/source/816-6408-10/handlers.htm#1120313 以下是来自Sun的文档: http : //docs.sun.com/source/816-6408-10/handlers.htm#1120313

Here is a solution that's adapted a bit from this page : 这是从此页面改编而成的解决方案:

window.onload = function () {
    document.forms.myForm.myField.onkeypress = keyTest;
}

function keyTest(e) 
{
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /[a-z0-9]/i;

    if (key != 8 && key != 9) return reg.test(keychar);
}

确保还对服务器执行了验证(假设有服务器部分),以防某些用户关闭了javascript。

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

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