Did you ever encounter an online form, which doesn’t let you enter invalid or special characters? Today, we are going to learn exactly that.

Don’t worry. It’s really easy.

But first, you are going to need jQuery.

You can download it from www.jquery.com or simply go to https://developers.google.com/speed/libraries/#jquery and get the CDN link for jQuery.

Create a new file index.html and include jQuery before the closing </body> tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

We can verify and restrict user input in two ways. The first method uses regular expressions and the second method uses ASCII value of characters.

Method 1

Let’s start with the first method. A regular expression is a sequence of a character used for pattern matching.

Regular Expression /^[A-Za-z0-9 ]+$/ would only match with the string that has A-Z, a-z ,0-9 or space. As no special character is being included in the expression, it won’t match against the string that has any special character.

  <input type="text" id="textbox">
  <div id="error_msg"></div>
$(document).ready(function(){

      $("#textbox").keypress(function (e) {

        var key = e.keyCode || e.which;       
        $("#error_msg").html("");

        //Regular Expression
        var reg_exp = /^[A-Za-z0-9 ]+$/;

        //Validate Text Field value against the Regex.
        var is_valid = reg_exp.test(String.fromCharCode(key));

        if (!is_valid) {
          $("#error_msg").html("No special characters Please!");
        }

        return is_valid;
      });
    });

Method 2

The letter and digits fall into the following ranges of ASCII codes: a-z (97-122), A-Z (65-90), 0-9(48-57). ASCII code for space is 32. Compare the ASCII value of allowed characters with the characters being entered. If the user enters a special character, let him know through an error message and skip that character.

    $(document).ready(function(){
      $("#textbox").keypress(function (e) {
        $("#error_msg").html("");
        var key = e.keyCode;
        $return = (key == 8 || key == 32 || (key >= 48 && key <= 57) || (key > 64 && key < 91) || (key > 96 && key < 123)  );
        if(!$return) {
          $("#error_msg").html("No special characters Please!");
          return false;
        }
      });
    });

Related Articles

How to capitalize the first letter of each word using JQuery and CSS

Working with checkboxes and radio buttons using jQuery

Create a Logoff/Logout Action in ASP.NET MVC

Last modified: February 12, 2019

Comments

Write a Reply or Comment

Your email address will not be published.