官术网_书友最值得收藏!

Restricting input character length

It is possible to limit the characters a user is able to input into a text field by utilizing jQuery's keypress events. In some situations, this can be a powerful user experience feature, as the user is visually aware of the characters that they cannot provide instead of having to wait for a response from the server informing them of this error.

Getting ready

Once again, we are going to need a blank HTML document with the latest version of jQuery to work through this recipe. Create recipe-6.html and ensure that you have jQuery downloaded and ready to go.

How to do it…

Learn how to restrict a user from entering certain characters into a text input using jQuery by performing the following steps:

  1. Add the following HTML code to your newly created recipe-6.html file that creates a basic HTML web page with a single input element:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Chapter 2 :: jQuery Events</title>
        <script src="jquery.min.js"></script>
        <script>
    
        </script>
    </head>
    <body>
    <input type="text" class="myInput" />
    </body>
    </html>
  2. Within the script tags of the HTML page, add the following JavaScript code, which binds a keypress event handler to the input and prevents any nonalphanumeric character input in the selected text input:
    $(function() {
        $('.myInput').keypress(function (event) {
          var regex = new RegExp("^[a-zA-Z0-9]+$");
          var key = String.fromCharCode(event.which);
          if (!regex.test(key)) {
            return false;
          }
        });
    });
  3. Open recipe-6.html in a browser and attempt to type a nonalphanumeric character into the input textbox; you will see that it is not possible to do so.

How it works…

We attach the keypress event handler to the .myInput element and specify the event variable as an argument as shown in the following code snippet:

$('.myInput').keypress(function (event) {

});

This allows us to specify commands to be executed on keypress when the .myInput field has focus.

We declare a regular expression variable which we can use to evaluate whether the entered character is alphanumeric.

var regex = new RegExp("^[a-zA-Z0-9]+$");

Each key on the keyboard has a unique numeric code that can be accessed using event.which. Then, to determine if the key pressed is alphanumeric, we need to retrieve its string value (for example, alphanumeric value for f is 102 ), which can be done with the following code:

var key = String.fromCharCode(event.which);

This now allows us to apply the regular expression and determine if it meets our alphanumeric requirements. If it does not, we prevent such key value from being entered by returning false as follows:

if (!regex.test(key)) {
  return false;
}

We allow the character to be displayed in the textbox if the pressed key was a valid alphanumeric character.

There's more...

It is important to understand that client-side validation such as this is a powerful user experience feature, but it should never be solely relied upon. Any validation done on the client side should always be mirrored on the server. This is because it is extremely easy for a user to bypass client-side validation. It is often as easy as turning off JavaScript from the browser settings. Remember that any client-side language such as JavaScript is completely open to manipulation by the end user. For this reason, client-side validation should only be used as a user experience enhancement and never a form of explicit validation of data input.

See also

  • Detecting key press events on inputs
主站蜘蛛池模板: 临夏市| 开封县| 金川县| 璧山县| 汤原县| 犍为县| 平塘县| 响水县| 江安县| 华安县| 和林格尔县| 瑞丽市| 任丘市| 抚州市| 忻州市| 沙雅县| 诸城市| 二连浩特市| 碌曲县| 德江县| 塔河县| 孝昌县| 丰宁| 新巴尔虎左旗| 白城市| 潜江市| 八宿县| 庆城县| 龙井市| 桃园市| 伊金霍洛旗| 新兴县| 大化| 常山县| 郯城县| 都江堰市| 张家口市| 珠海市| 清丰县| 丰都县| 宝兴县|