开发者

Validating user input with JavaScript

开发者 https://www.devze.com 2022-12-11 18:10 出处:网络
I need to make it so a user can ONLY type a-z0-9 into my input box. How can I make it so the user simply cannot type other characters? If this isn\'t possible, how can I 开发者_JS百科simply check the

I need to make it so a user can ONLY type a-z0-9 into my input box. How can I make it so the user simply cannot type other characters? If this isn't possible, how can I 开发者_JS百科simply check the input with regex?

Thanks!


Another notable solution is this alphanumeric plugin for jquery: http://itgroup.com.ph/alphanumeric/

Simple as $('#textField').alphanumeric();


If you use jQuery, there is a format plugin that does exactly what you need. Other than that, you can use onkeyup/onkeyup to call function which will validate input against regex pattern.


You can use the onKeyDown event. If you return false from your event handler, no key press event is fired and the key is "eaten".

Here are the docs from 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);
}


Make sure you also perform the validation on the server too (assuming there's a server part to this) in case some users have javascript turned off.

0

精彩评论

暂无评论...
验证码 换一张
取 消