There are multiple ways to validate user input string in order to allow only numbers. Lets say we have a string in variable myInput
, following are some tips you can use to check if the input string is only contains numbers.
Check for numbers while entering data
If you are using Winforms
and want to validate user input, then you can use TextBox's KeyPress
event.
private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') { e.Handled = true; } }
You can set e.Handled
property to true
if the character entered is not the desired one, it will suppress that key. You can use similar technique in JavaScript if you are working with ASP.NET.
Check for numbers if you have a string variable
In many cases, if you are not using Winforms application or you may need to inspect the string variable other than the KeyPress
event, then you can use one of following methods.
If the string variable contains a value within valid integer range, then you can use int.TryParse()
function to check if it has valid integer value.
private bool ValidateNumber(string myInput) { int val; if (int.TryParse(myInput, out val)) { return true; } else { return false; } }
Note: This method has limitation that the input is being checked only for valid integers, which can have a maximum value of 2,147,483,647
. For example, if you need to verify a string of 15 digits, then this method may not give you the desired result.
In order to validate a string with numbers having more digits, we can use the following options:
Char.IsDigit
can be used to check if the character at any specified position in string is a digit, and here we are using Linq function All
to our string, which will call Char.IsDigit
function for each character in the string, and hence can get the required output.
myInput.All(Char.IsDigit)
A more formal method can be used, i.e. Regular Expressions, which can give you more control in different scenarios. Here we are using Regular Expression "^[0-9]*$"
to match for numbers in input string.
System.Text.RegularExpressions.Regex.IsMatch(myInput, "^[0-9]*$")
I hope you find this post helpful, I welcome your comments or suggestions if you may find any more alternative(s) to validate numeric figures in a string.
ReplyDeletei read the above notes and clarify my doubts very well.in this information i observe lot of things about how to study.........thanks a lot
Angularjs Training in Chennai
Angular Training in Chennai
Data Science Course in Chennai
Data Science Training in Chennai
RPA course in Chennai
angularjs Training in OMR
angularjs Training in Porur