在textbox jQuery上验证keypress上的用户输入

时间:2011-04-01 04:32:57

标签: jquery jquery-validate

如何在jQuery中编码,这样用户就无法按下“。”键入文本框?

我可以在javascript中编码,在每个按键上,浏览器检查是否按下了一个键,如果它是点然后是子串(0,len-1),但它会闪烁! 我想完全阻止按键!

3 个答案:

答案 0 :(得分:5)

这应该有效。它没有经过跨浏览器测试:

$("#theTextBox").keyup(function() {
    if($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
});

You can try it here.

编辑:我认为这更好:

function doItPlease() {
    if ($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
}

$("#theTextBox").bind("keydown keyup", doItPlease);

Try the less sucky solution here.

编辑(再次):我赞成上述解决方案,因为我非常喜欢反馈方面。那就是说,我认为这就是你所追求的目标:

$("#theTextBox").keyup(function(e) {
    if (e.which != 190) {
        return true;
    }
    e.preventDefault();
});

Try it here.

答案 1 :(得分:3)

请看一下这个插件,以防止输入特定字符:http://www.itgroup.com.ph/alphanumeric/

另请参阅一般验证的验证插件:http://bassistance.de/jquery-plugins/jquery-plugin-validation/

答案 2 :(得分:1)

使用优秀的http://bassistance.de/jquery-plugins/jquery-plugin-validation/表单验证插件。

验证时需要做的就是将选项作为类名发出:

<强> HTML

<input id="test" type="text" class="required email"/>

requiredemail添加为类会将其验证为必须输入的必须输入的电子邮件。验证在您键入时完成。

<强>的jQuery

$('#test').validate()

这个插件的优点是你可以直接从Microsoft CDN访问js文件,因此你不必从服务器加载它。 http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js

相关问题