简体   繁体   English

jquery / JS只允许文本字段中的数字和字母

[英]jquery / JS allow only numbers & letters in a textfield

What would be the easiest way to allow only letters/numbers in a textbox. 在文本框中只允许字母/数字最简单的方法是什么。 We are using JS/jQuery, but don't want to use a validation plugin? 我们使用JS / jQuery,但不想使用验证插件?

My solution was this: 我的解决方案是:

jQuery('input[type="text"]').keyup(function() {
    var raw_text =  jQuery(this).val();
    var return_text = raw_text.replace(/[^a-zA-Z0-9 _]/g,'');
    jQuery(this).val(return_text);
});

Every time a user tries to enter anything other than a number, letter, space or underscore the function returns a string with the removed banded characters. 每次用户尝试输入除数字,字母,空格或下划线以外的任何内容时,该函数都会返回一个包含已删除的带状字符的字符串。

You can use a simple regex on form submit to evaluate the contents of the text box, show an error, and stop the form submit. 您可以在表单提交上使用简单的正则表达式来评估文本框的内容,显示错误,并停止表单提交。 Make a function out of the check and you can also apply it when the text box loses focus. 从检查中创建一个函数,您也可以在文本框失去焦点时应用它。 Do this very often and you'll find that you've reimplemented the validation plugin. 经常这样做,你会发现你已经重新实现了验证插件。

$(function() {
    $('form').submit( function() {
        return validateTB( $('#textbox'), true, $('#textboxError') );
    });

    $('#textbox').blur( function() {
        validateTB( $(this), true, $('#textboxError') );
    });

    function validateTB(tb,required,msg) {
        var $tb = $(tb);
        var re = '/^[a-z0-9]';
        if (required) {
           re += '+';
        }
        else {
           re += '*';
        }
        re += '$/';

        if ($tb.val().match(re) == null) {
           $(msg).show();
           return false;
        }
        $(msg).hide();
        return true;
    }
});

If you don't wanna use plugins - What about some plain old JS validation? 如果你不想使用插件 - 一些普通的旧JS验证怎么样?

I posted about this on my blog a while ago --> http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html 我刚刚在我的博客上发布了这个 - > http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html

You'll see that the function in my proposed solution takes a input field ID and a regex (and you'll have to come up with a regEx for your validation needs, should be pretty trivial if you want only aplhanumeric) and sets the background of the control to green or red depending on the outcome of the validation. 您将看到我提出的解决方案中的函数采用输入字段ID和正则表达式(并且您必须为验证需求提供regEx,如果您只需要aplhanumeric,则应该非常简单)并设置背景控制为绿色或红色取决于验证的结果。 I know it's not perfect but I think it's enough to get you going, and you can use it as a starting point to roll your own. 我知道它并不完美,但我认为这足以让你前进,你可以用它作为自己的起点。

I am sure there are mote elegant solutions using jQuery or plain JS but something along these lines has been working pretty well for me so far. 我确信使用jQuery或普通JS有很好的解决方案,但到目前为止,这些方面的东西对我来说一直很好。

Hope it helps. 希望能帮助到你。

Since tvanfossen's snippet triggers only on submit and Ian's is not as pretty as it could be, I just want to add a more cleaner approach: 由于tvanfossen的代码片段仅在提交时触发而且Ian的内容不尽如人意,我只想添加更清晰的方法:

HTML: HTML:

<input id="myinput" type="text">

JS (jquery): JS(jquery):

$('#myinput').keypress(function (e) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }
    e.preventDefault();
    return false;
});

This is a simple solution that will check the input on keyup and remove unwanted characters as the user types: 这是一个简单的解决方案,它将检查keyup上的输入并删除用户键入的不需要的字符:

<input class="usr" type="text id="whatever" name="whatever" />

        $(".usr").keyup(function() {
            var n = $(this).val();
            if ( n.match("^[a-zA-Z0-9 ]*$") == null ) {
                $(this).val(n.slice(0,-1));
            }
        });

The regex can be altered to suit specifications. 可以改变正则表达式以适应规范。

A variant on Ian's answer is a little more lightweight and shorter: Ian答案的变体更轻巧,更短:

function onlyAllowAlphanumeric() {
    this.value = this.value.replace(/[^a-zA-Z0-9 _]/g, '');
});

$('input[type="text"]').keyup(onlyAllowAlphanumeric);

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

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