Validating a Textbox field for only numeric input. - c#

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.
So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value is numeric:
else if (txtEvDistance.Text.Length == 0)
{
MessageBox.Show("Please enter the distance");
}
else if (cboAddEvent.Text //is numeric)
{
MessageBox.Show("Please enter a valid numeric distance");
}

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}

If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.

Here is another simple solution
try
{
int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}

You can do it by javascript on client side or using some regex validator on the textbox.
Javascript
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
Textbox (with fixed ValidationExpression)
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>

I agree with Int.TryParse but as an alternative you could use Regex.
Regex nonNumericRegex = new Regex(#"\D");
if (nonNumericRegex.IsMatch(txtEvDistance.Text))
{
//Contains non numeric characters.
return false;
}

You can do this way
// Check if the point entered is numeric or not
if (Int32.TryParse(txtEvDistance.Text, out var outParse))
{
// Do what you want to do if numeric
}
else
{
// Do what you want to do if not numeric
}

I have this extension which is kind of multi-purpose:
public static bool IsNumeric(this object value)
{
if (value == null || value is DateTime)
{
return false;
}
if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
{
return true;
}
try
{
if (value is string)
Double.Parse(value as string);
else
Double.Parse(value.ToString());
return true;
}
catch { }
return false;
}
It works for other data types. Should work fine for what you want to do.

if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
{
lblMessage.Text = string.Empty;
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Maroon;
lblMessage.Text = "You have not entered a number";
return;
}

Here's a solution that allows either numeric only with a minus sign or decimal with a minus sign and decimal point. Most of the previous answers did not take into account selected text. If you change your textbox's ShortcutsEnabled to false, then you can't paste garbage into your textbox either (it disables right-clicking). Some solutions allowed you to enter data before the minus. Please verify that I've caught everything!
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
return true;
}
else
{
// If it's not the first character, then it must be a digit or backspace
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
return false;
else
return true;
}
}
else
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
{
// If the first character is a decimal point or digit, AND
// if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
return false;
else
return true;
}
}
else
{
// If it's not the first character, then it must be a digit or backspace OR
// a decimal point AND
// if the text does not contain a decimal point or the selected text does contain a decimal point.
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
return false;
else
return true;
}
}
}

To check if the value is a double:
private void button1_Click(object sender, EventArgs e)
{
if (!double.TryParse(textBox1.Text, out var x))
{
System.Console.WriteLine("it's not a double ");
return;
}
System.Console.WriteLine("it's a double ");
}

I know this is an old question but I figured out I should pitch my answer anyways.
The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.
using System;
private bool ValidateText(string text){
char[] characters = text.ToCharArray();
foreach(char c in characters){
if(!char.IsNumber(c))
return false;
}
return true;
}

Use Regex as below.
if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
MessageBox.show("add content");
} else {
MessageBox.show("add content");
}

Related

TextBox with maxvalue

I want to make a TextBox which does not allow to enter a value above 100. Only numbers allowed, And a Numeric TextBox is not an option. This is my code for now:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } // only numbers
}
Any ideas?
You should use int.TryParse to see if the parsing is successful and then compare the value to see if it is below 100.
int number;
if(int.TryParse(textBox1.Text, out number))
{
if(number <= 100)
{
//in range
}
else
{
// not in range
}
}
else
{
//invalid number
}
You can also use double.TryParse or other TryParse method depending on the type, they are safe to use, since they will return a false if the parsing fails, instead of raising an exception.
Hello, here is my solution.
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if ((!char.IsDigit(c) ||
Convert.ToInt32(textBox.Text + e.KeyChar) >= 101 ||
textBox.Text == "0") && c != '\b')
e.Handled = true;
}
Finally. I found a solution:
int box_int = 0; Int32.TryParse(textBox1.Text, out box_int);
if (box_int > 1050 && textBox1.Text != "") { textBox1.Text = "1050"; }
You can enter only numbers and use arrows keys and backspace. If you enter a number > than 100 or less than 1, when you press enter it will be cancelled. Copy and Past with button key down is disabled and also mouse right click to prevent the user to paste in the text box is disabled/handled. This should solve your problem in full.
First of all set:
ShortcutsEnabled property of your text box to False
this will not allow mouse right click and ctrl+V for paste in your text box.
Then add the following code:
//prevent letters, special chars, punctuation, symbols, white spaces
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsLetter(e.KeyChar) ||
char.IsSymbol(e.KeyChar) ||
char.IsWhiteSpace(e.KeyChar) ||
char.IsPunctuation(e.KeyChar))
e.Handled = true;
}
{
//allows only numbers between 1 and 100
string value = txtType1.Text;
if (txtType1.Text !="")
{
if (Int16.Parse(value) < 1 )
{
txtType1.Text = "";
}
else if (Int16.Parse(value) > 100)
{
txtType1.Text = "";
}
}
}
}

Checking whether a text box contain only digits

I am done with this problem(using an alternative method). But still don't know why the following method is not working. Please help
Aim: when leave from a text box
check whether it contain only digits-then allow to leave.
If not show an error provider.
check whether string length is not more than 7 and not 0 -then allow to leave.
if not show an error provider.
Code that doesn't seem working is given below! :
private void textBox24_Validating(object sender, CancelEventArgs e)
{
bool result = true;
foreach (char y in textBox24.Text)
{
while (y < '0' || y > '9')
result = false;
}
if (result == false)
{
errorProvider4.SetError(textBox24, "Enter digits only");
textBox24.Focus();
}
else if (textBox24.Text.Length == 0)
{
errorProvider4.SetError(textBox24, "Enter the value");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox24, "Maximum length is 7 digits");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
problem with this code:
when I enter input other than digits, it gets stuck.
May be this wont be a big question. However help me.
code that now I am using:
private void textBox24_Validating(object sender, CancelEventArgs e)
{
int check = 123;
bool result = int.TryParse(textBox24.Text, out check);
if (result == false)
{
errorProvider4.SetError(textBox24, "Only digits are allowed");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox6, "Invalid value");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
inside while loop you have condition if true you set the result as true but loop running forever because condition again true.
foreach (char y in textBox24.Text)
{
while (condition) // this is run forever if true
result = false;
}
you can use break; if true case like below
foreach (char y in textBox24.Text)
{
while (condition){
result = false;
break;
}
}
Few more Suggestion..
TextBox control having property called MaxLength you can set it as 7 to limit user input up to 7 characters
if you need to allow only digits don't use int.TryParse method. if input with decimal points will pass the validation.
to check string contains only digits you can use code like if (textBox1.Text.ToCharArray().Any(c=>!Char.IsDigit(c)))
if validation fail you need to set e.Cancel = true;

C# Textbox validation should only accept integer values, but allows letters as well

if (textBox1.Text != "") // this forces user to enter something
{
// next line is supposed to allow only 0-9 to be entered but should block all...
// ...characters and should block a backspace and a decimal point from being entered....
// ...but it is also allowing characters to be typed in textBox1
if(!IsNumberInRange(KeyCode,48,57) && KeyCode!=8 && KeyCode!=46) // 46 is a "."
{
e.Handled=true;
}
else
{
e.Handled=false;
}
if (KeyCode == 13) // enter key
{
TBI1 = System.Convert.ToInt32(var1); // converts to an int
Console.WriteLine("TBI1 (var1 INT)= {0}", var1);
Console.WriteLine("TBI1= {0}", TBI1);
}
if (KeyCode == 46)
{
MessageBox.Show("Only digits...no dots please!");
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
}
else
{
Console.WriteLine("Cannot be empty!");
}
// If I remove the outer if statement and skip checking for an empty string, then
// it prevents letters from being entered in the textbox. I need to do both, prevent an
// empty textbox AND prevent letters from being entered.
// thanks, Sonny5
You didn't specify where this code runs, but my assumption would be it runs on key down. Since key down is received before the character is processed and the Text property is updated, your check for .Text == "" will prevent the rest of the validation running, at least for the first character.
You should move the check for empty value on a different event than the check for the key pressed.
I think you could use the IsDigit function.
Something along these lines:
string textBoxText = "12kj3";
if (!textBoxText.Equals(String.Empty)) // this forces user to enter something
{
foreach (char c in textBoxText.ToArray())
{
if (!Char.IsDigit(c))
{
//return false;
}
}
//return true;
}
else
{
Console.WriteLine("Cannot be empty!");
}
Hope you get the idea.
You can use the following RegEx to check that it is a number "^\d+$" and required.
bool bV=false;
private void textBox1_Validated(object sender, EventArgs e)
{
TextBox textBoxText = sender as TextBox;
if (!textBoxText.Equals(String.Empty))
{
foreach (char c in textBoxText.Text.ToArray())
{
if (!Char.IsDigit(c))
{
if (!bV)
{
MessageBox.Show("Input value not valid plase Insert Integer Value");
bV = true;
textBox1.Text = String.Empty;
break;
}
}
}
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
bV = false;
}

Validation-Textboxes allowing only decimals

I am using following code for validating textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = SingleDecimal(sender, e.KeyChar);
}
public bool SingleDecimal(System.Object sender, char eChar)
{
string chkstr = "0123456789.";
if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack)
{
if (eChar == ".")
{
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
{
return true;
}
else
{
return false;
}
}
return false;
}
else
{
return true;
}
}
Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?
here is the code I would use...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
You can make a method to check if it's a number.
Instead of checking for the . as a decimal separator you should get it from CurrentCulture object as it could be another character depending on where in the world you are.
public bool isNumber(char ch, string text)
{
bool res = true;
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
//check if it´s a decimal separator and if doesn´t already have one in the text string
if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
{
res = false;
return res;
}
//check if it´s a digit, decimal separator and backspace
if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
res = false;
return res;
}
Then you can call the method in the KeyPress event of the TextBox:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!isNumber(e.KeyChar,TextBox1.Text))
e.Handled=true;
}
create a component inherited from textbox and use this code:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && Text.IndexOf('.') > -1)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
Here is a Vb.Net version for #Eclipsed4utoo's answer
If (((Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 8 And Asc(e.KeyChar) <> 46)) Then
e.Handled = True
Exit Sub
End If
' checks to make sure only 1 decimal is allowed
If (Asc(e.KeyChar) = 46) Then
If (sender.Text.IndexOf(e.KeyChar) <> -1) Then
e.Handled = True
End If
End If
This codes for decimals. If you want to use float also, you just use double insteat int
And it will be delete automaticaly last wrong charachters
private void txt_miktar_TextChanged(object sender, TextChangedEventArgs e)
{
if ((sender as TextBox).Text.Length < 1)
{
return;
}
try
{
int adet = Convert.ToInt32((sender as TextBox).Text);
}
catch
{
string s = "";
s = (sender as TextBox).Text;
s = s.Substring(0, s.Length - 1);
(sender as TextBox).Text = s;
(sender as TextBox).Select(s.Length, s.Length);
}
}
How about using the example from MSDN?
Are u using the '.' as decimal seperator? if so than I don't know why you are using
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
Here some code from my app. It handle one more case as will related to selection
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\b')
return;
string newStr;
if (SelectionLength > 0)
newStr = Text.Remove(SelectionStart, SelectionLength);
newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1));
double v;
//I used regular expression but you can use following.
e.Handled = !double.TryParse(newStr,out v);
base.OnKeyPress(e);
}
here regex expression if like to use them instead of that easy type parsing
const string SIGNED_FLOAT_KEY_REGX = #"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$";
const string SIGNED_INTEGER_KEY_REGX = #"^[+-]?[0-9]*$";
const string SIGNED_FLOAT_REGX = #"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$";
const string SIGNED_INTEGER_REGX = #"^[+-]?[0-9]+$";
I believe this is the perfect solution as it not only confines the text to numbers, only a leading minus sign, and only one decimal point, but it allows the replacement of selected text if it contains a decimal point. The selected text still cannot be replaced by a decimal point if there is a decimal point in the non-selected text. It allows a minus sign only if it's the first character or if the entire text is selected.
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// only allow numbers
if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
return true;
}
else
{
// allow a minus sign if it's the first character or the entire text is selected
if (e.KeyChar == '-' && (txt.Text == "" || txt.SelectedText == txt.Text))
return false;
// if a decimal point is entered and if one is not already in the string
if ((e.KeyChar == '.') && (txt.Text.IndexOf('.') > -1))
{
if (txt.SelectedText.IndexOf('.') > -1)
// allow a decimal point if the selected text contains a decimal point, that is the
// decimal point replaces the selected text
return false;
else
// don't allow a decimal point if one is already in the string and the selected text
// doesn't contain one
return true;
}
// if the entry is not a digit
if (!Char.IsDigit(e.KeyChar))
{
// if it's not a decimal point and it's not a backspace then disallow
if ((e.KeyChar != '.') && (e.KeyChar != Convert.ToChar(Keys.Back)))
{
return true;
}
}
}
// allow only a minus sign but only in the beginning, only one decimal point, any digit, a
// backspace, and replace selected text.
return false;
}
Here is a vb.net version that allows negative decimal figure, prevent copy and paste while making sure the negative sign is not in the middle of the text or the decimal point not at the beginning of the text
Public Sub Numeric(textControl As Object, e As KeyPressEventArgs)
Dim Index As Int32 = textControl.SelectionStart
Dim currentLine As Int32 = textControl.GetLineFromCharIndex(Index)
Dim currentColumn As Int32 = Index - textControl.GetFirstCharIndexFromLine(currentLine)
Dim FullStop As Char
FullStop = "."
Dim Neg As Char
Neg = "-"
' if the '.' key was pressed see if there already is a '.' in the string
' if so, dont handle the keypress
If e.KeyChar = FullStop And textControl.Text.IndexOf(FullStop) <> -1 Then
e.Handled = True
Return
End If
'If the '.' is at the begining of the figures, prevent it
If e.KeyChar = FullStop And currentColumn <= 0 Then
e.Handled = True
Return
End If
' if the '-' key was pressed see if there already is a '-' in the string
' if so, dont handle the keypress
If e.KeyChar = Neg And textControl.Text.IndexOf(Neg) <> -1 Then
e.Handled = True
Return
End If
'If the '-' is in the middle of the figures, prevent it
If e.KeyChar = Neg And currentColumn > 0 Then
e.Handled = True
Return
End If
' If the key aint a digit
If Not Char.IsDigit(e.KeyChar) Then
' verify whether special keys were pressed
' (i.e. all allowed non digit keys - in this example
' only space and the '.' are validated)
If (e.KeyChar <> Neg) And (e.KeyChar <> FullStop) And (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
' if its a non-allowed key, dont handle the keypress
e.Handled = True
Return
End If
End If
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Numeric(sender, e)
End Sub
try this with asp:RegularExpressionValidator controller
<asp:RegularExpressionValidator ID="rgx"
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic" ValidationGroup="lnkSave"></asp:RegularExpressionValidator>

Not allow zero in textbox

I need a textbox which only the user can permit to enter integers. But the user can't enter zero. i.e, he can enter 10,100 etc. Not 0 alone.
How can I make event in KeyDown?
The way you plan to do this, is very annoying for a user. You're guessing what a user wants to enter, and act upon your guess, but you can be so wrong.
It also has holes, for example, a user can enter "10" and then delete the "1". Or he could paste in a "0" -- you do allow paste, don't you?
So my solution would be: let him enter any digit he likes, any way he likes, and validate the input only after he finished, for example, when the input loses focus.
Why not using a NumericUpDown and make the following settings:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
Use int.TryParse to convert the text into a number and check if that number is not 0. Use the Validating event for the check.
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
EDIT:
Okay, since you use WPF you should take a look at how to implement validation the WPF way. Here is a validation class that implements the above logic:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
This is another variation on the theme:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text == "" && e.KeyChar == '0')
{
e.Handled = true;
return;
}
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
return;
}
}
not nice but it works

Categories

Resources