最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - prevent typing non ascii characters in a textbox - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Oct 2, 2009 at 13:31 BlertaBlerta 2,1905 gold badges23 silver badges34 bronze badges 2
  • 1 Do you need to do this client-side? Why not do it server-side? That way you can still strip out characters you don't want even if the user has JavaScript turned off. Also, preventing users from entering non-ASCII characters seems a bit naïve, a bit passé ;-) – Dominic Rodger Commented Oct 2, 2009 at 13:36
  • What do you mean by "non-ASCII"? Unicode characters? Or simply characters beyond the 0-127 range? – Ateş Göral Commented Oct 2, 2009 at 14:15
Add a ment  | 

2 Answers 2

Reset to default 2

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

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

发布评论

评论列表(0)

  1. 暂无评论