Prevent character input without ascii in text box

Since I think that people are faced with this a lot of time before I did this, and there might be some kind of standard solution. Can someone give any hint on how to prevent the user from entering characters without ascii in the text box.

+1
source share
2 answers

I personally find mastering with standard interaction modes a bit annoying, but if you have to filter keyboard input, you can do this by intercepting keypress events and canceling the ones you don't want:

var allowed = /[a-zA-Z0-9]/; // etc.

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // Cross-browser
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is the key allowed?
        if (!allowed.test(char)) {
            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

And this is more concise and beautiful with jQuery:

var allowed = /[a-zA-Z0-9]/; // etc.

$(function () {
    var input = document.getElementById("test");

    $("#input").keypress(function (e) {
        // Is the key allowed?
        if (!allowed.test(String.fromCharCode(e.keyCode || e.which))) {
            // Cancel the original event
            e.preventDefault();
            e.stopPropagation();
        }
    });
});
+2
source

ASP.NET, RegularExpressionValidator, ASP.NET. - , , , . .

:

<asp:TextBox id="txtItem" runat="server" MaxLength="50"></asp:TextBox>
<asp:RegularExpressionValidator id="SomeFieldValidator" runat="server" 
  CssClass="SomeClass" ControlToValidate="txtItem" 
  ErrorMessage="This field only accepts ASCII input." Display="Dynamic"
  ValidationExpression="^[A-Za-z0-9]*$"></asp:RegularExpressionValidator>

txtItem TextBox, . SomeFieldValidator ControlToValidate txtItem. ValidationExpression - , TextBox. JScript .NET Regex. , - . , - ^ [\ w\s] * $, ASCII.

, ASPX- , , .

RequiredFieldValidator. TextBox, RegularExpressionValidator. TextBox.

.

RegularExpressionValidator Control MSDN

FieldValidator Control MSDN

MSDN ( )

JavaScript RegExp

+1

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


All Articles