Loading...

TapGen

Free online tutorials

img

We are going to create an input box that only contains the characters. it will Block special characters and the space from input fields with jQuery.

To block special characters from input fields you need to use regexregex is an object and method for pattern matching and manipulation. 

You can use the input event to filter out unwanted characters as the user types. Below is a simple example of how you can achieve this.

 

                                        
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Block Special Characters</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        input {
            padding: 8px;
            margin: 10px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
<input type="text" id="username_go" placeholder="Type here..." />
<script type="text/javascript">
$('input#username_go').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});
</script>    
</body>
</html>
 
                                    

To restrict typing special characters and spaces inside an input field using jQuery, you can use the code.

 

 

 

=================================
Share This Article
icon

New to Communities?

Join the community