views:

992

answers:

2

Since I think people have encounter it lots of time before I did and there may be some standart solution.. Can anybody give any hint direction how to prevent a user from typing non ascii characters in a textbox.

+2  A: 

I personally find tinkering with standard modes of interaction a bit annoying, but if you must filter keyboard input, you can do it by intercepting key press events and canceling the ones that 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 it's more concise and prettier 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();
        }
    });
});
Ates Goral
your regex should be "var allowed = /[a-zA-Z0-9]/;"
Vlad
@Vlad: Thanks for noticing! Fixed.
Ates Goral
A: 

If you're looking for a concise ASP.NET solution, you can use the RegularExpressionValidator control to restrict the contents of an ASP.NET TextBox. You don't have to write any server or client side code other than the page tag definition and the regular expression used for validation. Validation will get checked at both sides for you.

For example:

<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>

In this snippet, txtItem is the TextBox that needs validation. the SomeFieldValidator control is linked using the ControlToValidate attribute to the txtItem control. The ValidationExpression attribute is the regular expression that is used to enforce the contents of the TextBox. Per the documentation, this expression needs to be written to be compatible with both JScript and .NET Regex regular expressions. Also, I've only set the regular expression here to alpha-numeric characters. You might want to consider using something like ^[\w\s]*$ instead- if you are actually interested in printable characters instead of just ASCII.

A side benefit to using this technique is that you can also insert these validators into .aspx pages of updatable applications, without requiring anything other than an App Pool restart.

Also handy is the RequiredFieldValidator control. You can link these with TextBox controls that also have a RegularExpressionValidator attached. These handle the case of requiring input in a TextBox.

Here are some reference links.

RegularExpressionValidator Control at MSDN

RequiredFieldValidator Control at MSDN

Character Classes at MSDN (for Regular Expressions)

JavaScript RegExp Object Reference

meklarian