Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hi all please help me,

i have to validate textbox in asp.net through regular expression or javascript
that user can not enter any alphabets. They can only enter decimal number into textbox.
Posted

hi

u try this

VB
Private Sub txtinput_TextChanged(sender As Object, e As System.EventArgs) Handles txtinput.TextChanged



       If (txtinput.Text) Like ("*[!0-9,.]*") Then

           txtinput.Text = ""
           MessageBox.Show("enter string value")
       End If


   End Sub

only number and . and , are allowed
if u no need , and . means
write coding as
If (txtinput.Text) Like ("*[!0-9]*") Then


i think this will help u

happy coding...
 
Share this answer
 
v2
u should use javascript function :

C#
function fnAllowDigitsOnly(key)
{

     
        var keycode = (key.which) ? key.which : key.keyCode;
        if((keycode<48||keycode>57)&&(keycode!=8))
         {
            return false;
         }
}


// .cs code on page load 

if(!IsPostBack)
{
 txtextension.Attributes.Add("onkeypress", "return fnAllowDigitsOnly(event)");
}
 
Share this answer
 
You can done this in following ways:
1.AjaxFilteredTextBoxExtender

here you first add reference of ajax toolkit and this extender.
you can set ValidChars to "." for decimal which allo user to enter numeric value with decimal point.
VB
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
    TargetControlID="TextBox3"
    FilterType="Custom, Numbers"
    ValidChars="." />


2.using javscript

<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
var temp = obj.value;

// avoid changing things if already formatted correctly
var reg0Str = '[0-9]*';
if (decimalPlaces > 0) {
reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
} else if (decimalPlaces < 0) {
reg0Str += '\\.?[0-9]*';
}
reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
reg0Str = reg0Str + '$';
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;

// first replace all non numbers
var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
var reg1 = new RegExp(reg1Str, 'g');
temp = temp.replace(reg1, '');

if (allowNegative) {
// replace extra negative
var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
var reg2 = /-/g;
temp = temp.replace(reg2, '');
if (hasNegative) temp = '-' + temp;
}

if (decimalPlaces != 0) {
var reg3 = /\./g;
var reg3Array = reg3.exec(temp);
if (reg3Array != null) {
// keep only first occurrence of .
// and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
reg3Right = reg3Right.replace(reg3, '');
reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
}
}

obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;

if(window.event) {
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if(e.which) {
key = e.which;
isCtrl = e.ctrlKey;
}

if (isNaN(key)) return true;

keychar = String.fromCharCode(key);

// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}

reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

return isFirstN || isFirstD || reg.test(keychar);
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>


<input type="text" name="price" value="" size="10" onblur="extractNumber(this,2,false);" onkeyup="extractNumber(this,2,false);" onkeypress="return blockNonNumbers(this, event, true, false);" />
 
Share this answer
 
Use FilteredTextBoxExtender, which is available through AJAX Control Toolkit.
Check this link for more details :-

http://ajaxcontroltoolkit.codeplex.com/SourceControl/changeset/view/1014bf767f65#SampleWebSites%2fAjaxControlToolkitSampleSite%2fFilteredTextBox%2fFilteredTextBox.aspx[^]
 
Share this answer
 
ASP.NET
<asp:textbox id="TextBox1" runat="server" style="z-index: 100; left: 259px; position: absolute;<br mode=" hold=" />top: 283px" validationgroup="check" xmlns:asp="#unknown"></asp:textbox>

<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" controltovalidate="TextBox1" xmlns:asp="#unknown">
ErrorMessage="Please Enter Only Numbers" Style="z-index: 101; left: 424px; position: absolute;
top: 285px" ValidationExpression="^\d+$" ValidationGroup="check"></asp:regularexpressionvalidator>

i think this code is helpfull to u...

Regard
Sham
:)
 
Share this answer
 
v2
Try this

XML
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                    ControlToValidate="TextBox1" ErrorMessage=" Enter Decimal Values Only"
                    ValidationExpression="/^(?:\d*\.\d{1,2}|\d+ $/"></asp:RegularExpressionValidator>
 
Share this answer
 
And the issue? You should have tried at least once.

Not just that, see how many search results are there for the keyword: enter decimal number into textbox.[^]


First link: Allow only numbers and dot in script[^]

Further, there are free regex tools online /stand alone that you can use to write correct regex.
 
Share this answer
 
There is a control called RegularExpressionValidator available with ASP.NET. Use that to validate the TextBox. Make sure you set the ControlToValidate and the ValidationExpression for it.

This will validate on both the client side and the server side.

For more information about RegularExpressionValidator, try the following link:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator(v=vs.90).aspx[^]

If you wish to validate only via JavaScript, see the following link:

http://www.devarticles.com/c/a/JavaScript/Form-Validation-with-JavaScript-Regular-Expressions-Part-1/[^]
 
Share this answer
 
try this:

XML
<asp:textbox id="txt_qty" runat="server" columns="2"></asp:textbox>

<asp:requiredfieldvalidator id="r1" runat="server" errormessage="*" controltovalidate="txt_qty"></asp:requiredfieldvalidator>

<asp:regularexpressionvalidator id="regular1" controltovalidate="txt_qty" runat="server" errormessage="*" validationexpression="^\d+$"></asp:regularexpressionvalidator>



this way your problem will solve...
 
Share this answer
 
v2
Comments
Rajeev prasad yadav 26-Sep-12 2:40am    
Hi mits,
this expression is working properly through regular message.
But i want to that user can not enter any thing in textbox if they are entering any alphabets.
Hadi Basiri 26-Sep-12 8:52am    
use of asp:requiredfieldvalidator control.you can enable or disable it by javascript .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900