Jquery / JS only allows numbers and letters in a text field

Which would be the easiest way to allow only letters / numbers in a text box. We use JS / jQuery but don’t want to use the validation plugin?

+3
source share
6 answers

You can use a simple regular expression to represent the form to evaluate the contents of the text field, show an error, and stop submitting the form. Run the function from validation, and you can also apply it when the text field loses focus. Do this very often and you will find that you have redefined 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;
    }
});
+4
source

My solution was as follows:

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);
});

, -, , , , .

+4

- JS?

β†’ http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html

, ( regEx , , aplhanumeric) . , , , , , , .

, mote jQuery JS, - .

, .

+3

Since tvanfossen triggers run only on submit and Ian is not as pretty as it might be, I just want to add a cleaner approach:

HTML:

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

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;
});
+1
source

This is a simple solution that checks keyboard input and removes unwanted characters by user type:

<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 regular expression can be changed according to the specifications.

0
source

The answer option for Ian is a bit lighter and shorter:

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

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

Source: https://habr.com/ru/post/1727147/


All Articles