How to allow only letters and numbers in a text box

Asked

Viewed 2,125 times

1

I’m making a form and the first solution I saw was to create a keyboard with buttons with only letters numbers the erase button and the space button but now what I really wanted was a box that allowed only numbers and letter because it makes itif very boring to write with the virtual keyboard how can I do this on a web page?

Any idea? or the virtual keyboard with buttons is the best idea?

<form>
<input type="text" required="required" name="text" pattern="[a-z\s]+$" />
</form>
  • I’m not the one who said no, but commenting on that question takes the focus off your problem, and goes downvote. If you want someone to help you, avoid commenting votes within the question.

  • But the reality is I won’t know what’s wrong with just votes

  • 1

    How about adding what you’ve already tried to do? It would greatly improve the question.

1 answer

3


You can create a regular expression to limit your input to accepting only the characters you want:

Js:

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

    e.preventDefault();
    return false;
});

Fiddle: https://jsfiddle.net/b0aLrpkn/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.