Introduction
In this article we will learn how to restrict the alphabets and special character on asp textbox control and restrict the paste option on textbox. Insert only numeric value 0-9 in textbox control using regex or Regular Expression.
Previous Updates
In previous articles we have learnt Showing Chart With Database In Asp.Net Using C#. Maintain state of dynamic added userConrol in asp.net using c#. Load the Usercontrol In Aspx Page. Get TextBox , Dropdown, CheckBox control Values In Aspx.cs Page From User Control Using C#.
Regular expression (regex) is a pattern which match the input text.
Allow only numeric value in Textbox Using Regex with JavaScript
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function isNumberKey(evt) {
var regex = new RegExp("^[0-9]");
var str = String.fromCharCode(!evt.charCode ? evt.which : evt.charCode);
if (!regex.test(str)) {
alert('Only numbers allowed.')
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Regex Using JavaScript</h3>
<asp:TextBox ID="myTxt" runat="server" onkeypress="return isNumberKey(event)">
</asp:TextBox>
</div>
</form>
</body>
</html>
|
In the above javascript example i used a onkeypress event of textbox ang call a javascript function isNumberKey to validate the string value pressed or not. If a string key pressed it will gave ther alert message only numbers allowed.
Allow only numeric value in Textbox Using ServerSide regex
<asp:TextBox ID="myTxt" runat="server" OnTextChanged="myTxt_TextChanged"></asp:TextBox>
|
On Aspx.cs Page
protected void myTxt_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch("^[0-9]", myTxt.Text))
{
myTxt.Text = string.Empty;
}
}
|
For server side validation here i use the simplest and easiest way. By using TextChanged event you can achieve this. every time you press any key asp.net fires the TextChanges event and if it is string value then it will clear the text.
0 comments:
Post a Comment