How to only allow letters and numbers in a text box

1

I am making a form and the first solution I saw was to create a keyboard with buttons with only letter numbers the delete button and the space button but now what I really wanted was a box that allowed only numbers and letter because it becomes very annoying to write with the virtual keyboard how can I do it on a web page?

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

<form>
<input type="text" required="required" name="text" pattern="[a-z\s]+$" />
</form>
    
asked by anonymous 11.03.2016 / 22:01

1 answer

3

You can create a regular expression to limit your input to only accepting 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: link

    
11.03.2016 / 22:36