Wednesday, 26 March 2014

How to check special characters in TextBox using JQuery

In this article I will explain how to check special characters in ASP.NET TextBox using JQuery

JQuery is very lightweight library. JQuery is a matured open source library that makes life easy when doing some client side programming or scripting. It simplifies the way JavaScript is written. It is light weight, fast and works on modern browsers, thus it’s widely accepted among the web developers and even Visual Studio 2010 and ASP.net 4.0 now come with it.

Below is the JQuery function for Special characters verification code

  $(function () {
            $('.view').blur(function () {
                var str = $('#txtName').val();
                if (/^[a-zA-Z0-9- ]*$/.test(str) == false) {
                    alert('String Contains illegal Characters.');
                }
                else {
                }
            })
        })


The above code we are using Blur event for finding special character.

To check if string contains special characters we need to write the code like as shown below is the Total code.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Check string contains special characters in TextBox</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('.view').blur(function () {
var str = $('#txtName').val();
if (/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('String Contains illegal Characters.');
}
else {
}
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
Check Special Characters :
<asp:TextBox runat="server" CssClass="view" ID="txtName"></asp:TextBox>       
</form>
</body>

</html>

Out Put :

No comments:

Post a Comment