jQuery-验证按键上的字符? [英] jquery - validate characters on keypress?

查看:70
本文介绍了jQuery-验证按键上的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单文本字段,我只允许输入数字和字母(即,没有#$!等).有没有一种方法抛出错误并防止按键实际输出任何东西如果用户尝试使用数字和字母以外的其他字符?我一直在尝试找到一个插件,但还没有真正找到能做到这一点的东西...

I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if the user tries to use any character other than numbers and letters? I've been trying to find a plugin, but haven't really found anything that does this...

推荐答案

$('input').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; } ) );
});


这里还有一些其他好的答案,将阻止输入.

There are some other good answers here that will prevent the input from taking place.

由于您也想显示一个错误,所以我已经更新了我的.替换可以使用函数而不是字符串.该函数运行并返回一个替换值.我添加了alert来显示错误.

I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an alert to show the error.

http://jsfiddle.net/ntywf/2/

这篇关于jQuery-验证按键上的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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