Solution: How to remove special characters from textbox using JavaScript (onchange,onkeyup) | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 

Solution: How to remove special characters from textbox using JavaScript (onchange,onkeyup)

Monday

 Client side validation: Remove special characters from textbox before save:
                                                         Sometime you might come into a situation to remove the specials characters in the textbox while users give the input. Below JavaScript sample code will help you to remove those char from textbox. The following script delete all the special character  on textbox "onkeyup" event.






Source code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Remove Special Characters from the Textbox - Coding cluster</title>
    <script language="javascript" type="text/javascript">
        function deleteSpecialChar(txtName) {
            if (txtName.value != '' && txtName.value.match(/^[\w ]+$/) == null) 
            {
                txtName.value = txtName.value.replace(/[\W]/g, '');
            }
        }
    </script>
</head>
<body>
    <form id="form1" >
    <div>
        <input id="txtName"  type="text" onkeyup="javascript:deleteSpecialChar(this)" />

    </div>
    </form>
</body>
</html>
Demo:Remove Special Characters from the Textbox - Coding cluster
Enter some text with special characters

That's all. If this post is useful for you , please share this knowledge to your friends. Thanks!

3 comments:

Waleed Barakat said...

Thank you, this is very good and helpful.

Waleed Barakat said...

Hello,
I have modified the script a little bit to be able to add some characters and line break if i used the script in textarea Also if you're an Arabic language user you can use it too.

Modification:
1- Adding
to textarea.
2- Enabling Arabic language characters.
3 Adding some more special chars like comma and dash

Here is the modification:
if (txtName.value != '' && txtName.value.match(/^[\w ء-ي-,.\n]+$/) == null)

Anonymous said...

I need the code like i can enter accept special char only dot(.) symbol can u reply me as soon as poosible

Post a Comment

Share your thoughts here...

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets