C# Masked TextBox with 0 or decimals - c#

Users have a textbox where they have to either enter a 0 or a value from 0.0001 to 0.9999.
What regex can I use here? I have looked at other examples but don't see anything like this one.

I'd say this is quite an effective solution. It allows for any strings entered that is either just a '0' or strings with '0.' followed by up to 4 of any digit.
Regex myRegex = new Regex("^(?:(?:0)|(?:0.[0-9]{1,4}))$");
Console.WriteLine("Regex: " + myRegex + "\n\nEnter test input.");
while (true)
{
string input = Console.ReadLine();
if (myRegex.IsMatch(input))
{
Console.WriteLine(input + " is a match.");
}
else
{
Console.WriteLine(input + " isn't a match.");
}
}
Here's a list of tests...

Try this one:
/(0)+(.)+([0-9])/g
Also see thing link that might helps you build you won expreession.
http://regexr.com/

Try this, it will do the work but I was not tested for all cases.
Regex _regex = new Regex("^[0]+(.[0-9]{1,4})?$");
if (input == "0" || _regex.IsMatch(input))
{
//Match
}
else
{
//Does not match
}
Note: input is a string, in your case Textbox.Text!

This is ready to use KeyPress event handler of TextBox control. It will prevent any input, except numeric between 0.0001 and 0.9999:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//Only one dot is possible
if ((sender as TextBox).Text.Contains('.') && (e.KeyChar == '.')) e.Handled = true;
//Only numeric keys are acceptable
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) e.Handled = true;
//Only one zero in front is acceptable, next has to be dot
if (((sender as TextBox).Text == "0") && (e.KeyChar == '0')) e.Handled = true;
double value = 0;
string inputValue = (sender as TextBox).Text + e.KeyChar;
if ((sender as TextBox).Text.Length > 0)
{
//Just in case parse input text into double
if (double.TryParse(inputValue, out value))
{
//Check if value is between 0.0001 and 0.9999
if (value > 0.9999) e.Handled = true;
if (((sender as TextBox).Text.Length > 4) && (value < 0.0001)) e.Handled = true;
}
}
else if (e.KeyChar != '0')
{
e.Handled = true;
}
}

Related

Input only digits and control buttons

I want to input Salary with any value: 550,49, 2222,12, 9,3 and so on. But need to use control button like this: ,, backspace, ctrl + c, ctrl + v, ctrl + a.
Salary is TextBox with ShortcutsEnabled = true and event:
private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
char number = e.KeyChar;
if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44)
//digits, BackSpace and ,
{
e.Handled = true;
}
}
If remove this condition, the specified combinations will work. But not only numbers are entered.
Should I add tracking of all combinations here? Or is it possible to implement this task in another way?
MaskedTextBox requires a fixed number of characters with some "mask". But the Salary is different. Can be **,**, ******,* or *** and etc.
UPDATE
Prevent entering more than two numbers after the decimal point
if (number < ' ')
{
return;
}
if (number >= '0' && number <= '9')
{
if (this.Text.Contains(',')
&& this.SelectionLength == 0
&& this.SelectionStart > this.Text.IndexOf(',')
&& this.Text.Length - this.Text.IndexOf(',') > 2)
{
e.Handled = true;
}
return;
}
Please, don't use magic numbers like 47, let's work with characters. We should allow these characters:
'0'..'9' range (numbers)
control characters (which are below space ' ') for tab, backspace etc.
',' (comma) as a decimal separator
All the other characters should be banned.
Code:
private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
char number = e.KeyChar;
TextBox box = sender as TextBox;
if (number >= '0' && number <= '9' || number < ' ')
return; // numbers as well as backspaces, tabs: business as usual
else if (number == ',') {
// We don't want to allow several commas, right?
int p = box.Text.IndexOf(',');
// So if we have a comma already...
if (p >= 0) {
// ... we don't add another one
e.Handled = true;
// but place caret after the comma position
box.SelectionStart = p + 1;
box.SelectionLength = 0;
}
else if (box.SelectionStart == 0) {
// if we don't have comma and we try to add comma at the 1st position
e.Handled = true;
// let's add it as "0,"
box.Text = "0," + box.Text.Substring(box.SelectionLength);
box.SelectionStart = 2;
}
}
else
e.Handled = true; // all the other characters (like '+', 'p') are banned
}
Please, note, that there is possibility to Paste incorrect value (say, "bla-bla-bla") into TbSalary TextBox; to prevent it you can use TextChanged event:
private void TbSalary_TextChanged(object sender, EventArgs e) {
TextBox box = sender as TextBox;
StringBuilder sb = new StringBuilder();
bool hasComma = false;
foreach (var c in box.Text)
if (c >= '0' && c <= '9')
sb.Append(c);
else if (c == ',' && !hasComma) {
hasComma = true;
if (sb.Length <= 0) // we don't start from comma
sb.Append('0');
sb.Append(c);
}
string text = sb.ToString();
if (!text.Equals(box.Text))
box.Text = text;
}

Textbox cannot empty or enter digit 0 c#

i use this code :
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Length == 0)
{
MessageBox.Show("Textbox Cannot Empty or digit 0");
textBox5.Focus();
}
else
{
MessageBox.Show("Success!");
}
e.Handled = true;
}
}
when I empty the textbox appears messagebox I expected . but when I enter the number/digit "0" appears messagebox success ? for validation i used numeric. for validation I only want to use the numbers 1-9. anybody can help me?
If you want to validate numbers and allow only integers between 1 and 9, you should use int.TryParse:
if (e.KeyChar == 13)
{
int number;
if(int.TryParse(textBox5.Text, out number) && number >= 1 && number <= 9)
{
MessageBox.Show("Success!");
}
else
{
MessageBox.Show("Textbox must contain an integer between 1 and 9");
textBox5.Focus();
}
e.Handled = true;
}
Side-note: || textBox5.Text.Length == 0 is redundant since string.IsNullOrWhiteSpace(textBox5.Text) checks that already.
Your problem is, that IsNullOrWhiteSpace checks only for null, not for the char '0'. If you want to check the digit too, you need to check in addition for textBox5.Text.Equals("0"):
if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Equals("0"))
{
MessageBox.Show("Textbox Cannot Empty or digit 0");
textBox5.Focus();
}
else
{
MessageBox.Show("Success!");
}
e.Handled = true;
Edit: Here's a .NET Fiddle
Q:
what if the digits entered are 00000 ??
A:
You can use int.TryParse as in the suggestion of Tim Schmelter
Or you can use the following Regex for vaidation: \^0*$\
Again the .NET Fiddle
Here you need: using System.Text.RegularExpressions;
if (string.IsNullOrWhiteSpace(textBox5.Text) || Regex.Match(textBox5.Text, "^0*$").Success)
{
MessageBox.Show("Textbox Cannot Empty or digit 0");
textBox5.Focus();
}
else
{
MessageBox.Show("Success!");
}
e.Handled = true;
if (string.IsNullOrWhiteSpace(textBox5.Text) || textBox5.Text.Length == 0)
{
MessageBox.Show("Textbox Cannot Empty or digit 0");
textBox5.Focus();
}
else
{
MessageBox.Show("Success!");
}
In this piece of code you're checking if the text length is 0
// "" will have length 0
// "0" will have length 1
If you want to check if you have the digit 0 in that box you need to check the following:
if (string.IsNullOrWhiteSpace(textBox5.Text) ||
textBox5.Text == "0")
textBox5.Text.Length == 0 // you don't need this anymore if youre using IsNullOrWhiteSpace as IsNullOrWhiteSpace checks for null, string.Empty, white spaces
Of course the most beautiful way to check that is to try to parse textBox5.Text and to see if you get a digit between 1 and 9 using the following code:
int.TryParse(textBox5.Text, out number) && number > 0 && number < 10
private void textBox5_TextChanged(object sender, EventArgs e)
{
string[] removeCaracter = { "0",... };
foreach (var item in removeCaracter)
{
textBox5.Text = textBox5.Text.Replace(item, "");
textBox5.SelectionStart = textBox5.Text.Length ;
textBox5.SelectionLength = 0;
}
}

How to only allow entering number between 0-99.99

How can I restrict the user from entering anything, in a text box, other than a value between 0 to 99.99
My code seems to be working but, it will allow any number to be entered. It will allow only number and a dot once. But it will still allow a value greater than 99.99
Below my code:
private void InputMargin_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
// allow only number and dot
if ( ! char.IsControl(e.KeyChar)
&& ! char.IsDigit(e.KeyChar)
&& e.KeyChar != '.'
|| (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
)
{
//e.Handled = true;
double margin;
double.TryParse((sender as TextBox).Text, out margin);
if (margin >= 0 && margin <= 99.99)
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
catch
{
e.Handled = false;
}
}
why not use NumericUpDown control with DecimalPlaces property set to 2.
no need to add any additional coding like on textbox.
why are you using `&& e.KeyChar != '.' because doing so doesnot accepts '.' .just delete this because you have also used (sender as TextBox).Text.IndexOf('.') > -1 this accepts only one '.' in the whole textfield so the Right if statement will be.
if ( ! char.IsControl(e.KeyChar)
&& ! char.IsDigit(e.KeyChar)
|| (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
)
{
//Your Code
}

validate textbox with only decimal numbers (positive and negative)

I have a textbox in C# where the user can enter only decimal numbers (negative and positive).
I don't want to use MaskedText Box, I would rather implement this using the keypress event to validate inputs.
How can I achieve this?
Thanks,
*********EDIT*********++
private void mytextbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != '.' &&e.KeyChar!='-'))
{
e.Handled = true;
}
if (e.KeyChar == '.')
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
if (e.KeyChar=='-' && (sender as TextBox).SelectionStart > 0)
{
e.Handled = true;
}
}
TryParse for the various numeric types will tell you if the input is valid. For example, if you want to use a double:
private void OnKeyPress(...)
{
double parsedValue = 0;
if (double.TryParse(MyTextBox.Text, out parsedValue)
{
//Valid number entered, value in parsedValue
}
else
{
//Invalid number entered
}
}
This answer has a lot of other ways to accompish this: How do I make a textbox that only accepts numbers?

How restrict textbox in C# to only receive numbers and (dot "." or comma ","), after "." or "," only allow 2 number characters

i am trying develop a code to restrict TextBox using C# to only allow numbers entry + comma(",") or dot(".") + only 2 numbers after dot or comma
So this way see possible numbers that can entry:
3213,04 = OK
3211,664 = Not
32.31 = OK
32.3214 = Not
334,,00 = Not
3247,.00 = Not
214.,00 = Not
32.. = Not
8465,0 = Ok
654.0 = Ok
Understood My goal ?
I developed code bellow
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtValormetrocubico.TextLength >= 0 && (e.KeyChar == (char)Keys.OemPeriod || e.KeyChar == (char)Keys.Oemcomma))
{
//tests
}
else
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf(',') > -1)
{
e.Handled = true;
}
}
}
This is auxiliary function I have written
private bool alreadyExist(string _text , ref char KeyChar)
{
if (_text.IndexOf('.')>-1)
{
KeyChar = '.';
return true;
}
if (_text.IndexOf(',') > -1)
{
KeyChar = ',';
return true;
}
return false;
}
This your key press event handler
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar='s';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (txtValormetrocubico.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (txtValormetrocubico.SelectionStart== 0 ) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(txtValormetrocubico.Text , ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (txtValormetrocubico.SelectionStart != txtValormetrocubico.Text.Length && e.Handled ==false)
{
// '.' or ',' is in the middle
string AfterDotString = txtValormetrocubico.Text.Substring(txtValormetrocubico.SelectionStart);
if (AfterDotString.Length> 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(txtValormetrocubico.Text ,ref sepratorChar))
{
int sepratorPosition = txtValormetrocubico.Text.IndexOf(sepratorChar);
string afterSepratorString = txtValormetrocubico.Text.Substring(sepratorPosition + 1 );
if (txtValormetrocubico.SelectionStart > sepratorPosition && afterSepratorString.Length >1)
{
e.Handled = true;
}
}
}
}
I think you need something like Masked Textbox control here you have some references
http://msdn.microsoft.com/en-us/library/kkx4h3az.aspx
http://www.c-sharpcorner.com/uploadfile/mahesh/maskedtextbox-in-C-Sharp/
Another way to do what you want is to use regular expressions
Well you can create a general function and call it on keypress event this code is a general instance.
validate_textBox is a general function
private void validate_textBox(TextBox _text, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar = 's';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (_text.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (_text.SelectionStart == 0) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(_text.Text, ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (_text.SelectionStart != _text.Text.Length && e.Handled == false)
{
// '.' or ',' is in the middle
string AfterDotString = _text.Text.Substring(_text.SelectionStart);
if (AfterDotString.Length > 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(_text.Text, ref sepratorChar))
{
int sepratorPosition = _text.Text.IndexOf(sepratorChar);
string afterSepratorString = _text.Text.Substring(sepratorPosition + 1);
if (_text.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
{
e.Handled = true;
}
}
}
}
Then you can call function like this code for each textbox you have in the form
private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
{
validate_textBox(sender as TextBox, e);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
validate_textBox(sender as TextBox, e);
}
I don't know who is looking for this in 2021 but here is one solution overriding the ontextchange event! Cheers
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
String text = "";
Char[] chars = this.Text.ToString().ToCharArray();
int total_dots = 0;
int dot_pos = 0;
int char_pos = 0;
foreach (Char c in chars )
{
char_pos++;
if (Char.IsDigit(c))
{
if(dot_pos > 0) { //dot already exists
if (char_pos <= dot_pos + 2) //only accept two numbers after dot (3.99)
{
text += c.ToString();
}
}
else
{
text += c.ToString();
}
}
if(c == '.' || c == ',')
{
total_dots++;
if (char_pos > 1 && total_dots <=1) //only accept one dot and if the dot is not in first position
{
text += c.ToString();
dot_pos = char_pos;
}
}
}
this.Text = text;
this.SelectionStart = this.Text.Length;
}

Categories