I need to limit the number of digits allowed in my TextBox in C#.
I also need to create the validation so that it will resemble a mobile number, meaning it must begin with 07 and have a total of 11 digits.
Any suggestions?
You can use a MaskedTextBox to provide a controlled input value. A "07" followed by 11 digit mask would be \0\700000000000.
You don't have any code as example, so, I would type mine.
To limit the number of characters you should type this code:
private bool Validation()
{
if (textBox.Text.Length != 11)
{
MessageBox.Show("Text in textBox must have 11 characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}
If you want that text in your textBox begin with "07", you should type this code:
private bool Validation()
{
string s = textBox.Text;
string s1 = s.Substring(0, 1); // First number in brackets is from wich position you want to cut string, the second number is how many characters you want to cut
string s2 = s.Substring(1, 1);
if (s1 != "0" || s2 != "7")
{
MessageBox.Show("Number must begin with 07", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}
You can merge this in one method ofcource, and you can call it where ever you want. If you want to call in some method(for example when you click on accept button) just type this code:
private void buttonAccept_Click(object sender, EventArgs e)
{
if (Validation() == false) return;
}
Related
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;
I used from Error Provider in C# winform. in my form have textbox. error provider checked it that it contain two number. it means that input is digit and number of digit is two number. when input is 2 char , error provider is worked but when input is char and digit, error provider didn't worked.
please check my code.
private void textbox1_Leave(object sender, EventArgs e)
{
string text = textbox1.Text;
bool hasDigit = false;
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
// Call SetError or Clear on the ErrorProvider.
if (!hasDigit )
{
errorProvider1.SetError(textbox1, "Please enter digit");
}
else if(hasDigit)
{
if (text.TextLength != 2)
{
errorProvider1.SetError(textbox1, "Number of digit is two number");
}
else
errorProvider1.Clear();
}
}
So you want to ensure that all chars are digits. But you're checking only the first, if that's a digit you're breaking the loop:
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
Instead you could use Linq for this. Enumerable.All is made for this purpose:
bool allDigits = text.All(c => Char.IsDigit(c));
(but maybe i'm totally off the track since the question is not so clear imho)
May be My Question is not seems like a good one but here is the Description:
I am creating an application in this in a form i have a textbox which is taking input from user here is my Code
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = string.Format("{0:0.##}", "0.00");
}
this will show value in textbox at pageload:0.00
Now after this if i click on backspace button of keyboard then
if (e.KeyChar.ToString() == ".")
{
e.Handled = true;
int b = textBox1.Text.LastIndexOf("00");
textBox1.SelectionStart = b;
}
else
{
string abc = "0";
string a = textBox1.Text.TrimStart(abc.ToCharArray());
textBox1.Text = a;
}
this code will lead me to here the textbox has now: .00 only
but after this when i enter some value then it will take values as;
2334.3423424
but i want to do like
2334.34
it means value should replace .00 only and user cant enter value after that.
This piece of code will restrict your user in entering only 2 digits after the decimal in your textbox.
//In key press event:
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox tt = (TextBox)sender;
if (tt.Text.IndexOf('.') > -1 && tt.Text.Substring(tt.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
If you mean to say you want to round up a number up to two decimal places use Math.Round(Double, Int32) function.
In your case you could call
double value = Convert.ToDouble(textBox1.Text);
double finalValue = Math.Round(value, 2);
textBox1.Text = finalValue.ToString();
Also make sure you validate the user input and make sure the user only enters numeric values.
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");
}
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;
}