Regex for two characters - c#

How to construct a Regex to allow enter CA or CH?
Tried \bC(A|H) and C(A|H) but I need to validate it in the KeyPress event of the textbox like this;
private Regex _regex = new Regex(#"C(A|H)");
private void txtCaCh_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar))
return;
if (!_rolfRegex.IsMatch(e.KeyChar.ToString().ToUpper()))
e.Handled = true;
}

You can use
if (e.KeyChar != (char)8) // Not a backspace key
if (!Regex.IsMatch(txtCaCh.Text.ToUpper() + e.KeyChar.ToString().ToUpper(), #"^C[AH]?$")) // If the value is not CH or CA
e.Handled = true; // Do not let it pass
Inside the KeyPress event handler, txtCaCh.Text contains the value before adding the next key. So, to get the full value we need to add the newly pressed key value. After that, we can check if the value is the one we can accept.
^C[AH]?$
This regex accepts C or CA or CH values, so that we can type them in.
Then, you need to validate it at some other event with ^C[AH]$ (Leave event, for example).
Live validation cannot be performed at the same time as final validation.

instead of validating the e.KeyChar, validate the content of the control itself:
if(!_rolfRegex.IsMatch((sender as TextBox)?.Value.ToUpper())
e.Handled = true;

Your pattern must be ^C[AH]$. Start of input (^), folowing C, then A or H ([AH])and end of input ($).
private Regex _regex = new Regex(#"^C[AH]$");
private void txtCaCh_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar))
return;
var txtBox = (TextBox)sender;
if (txtBox.Text != null && _rolfRegex.IsMatch(txtBox.Text.ToUpper()))
{
// TODO now we have match, handle it
}
}

Related

How can I remove a character from a C#.net WPF textbox before it's shown?

I have a project in C#.net using a WPF textbox that validates a character like * as the first character entered. If this character is entered, the rest of the text is good but I cannot show nor use the character. How can I remove the character from the string early enough to not show it? I've attempted using the KeyDown event but while the event is active, there is no data to remove. And if I use the KeyUp event the data is shown for a second. I've previously used a KeyPress event in VB6 to achieve this which worked because the value was simultaneously in the code but not in the textbox. As far as I can tell a WPF textbox does not have this event. What can I do?
Code:
private void UserInput_KeyUp(object sender, KeyEventArgs e)
{
//get ascii value from keyboard input
int Ascii = (int)e.Key;
//get char value to know what to remove as a string
char CharAscii = (char)Ascii;
If(Ascii == InputPrefix)
{
PrefixValidated = true;
UserInput.Text = UserInput.Text.Replace(CharAscii.ToString(), string.Empty);
}
}
The same code is in the KeyDown event and I've tried it using one or the other and both.
it may be a bit of a rough solution but you could use a PreviewTextInupt event I belive.
private bool PrefixValidated = false;
private string CheckUserInput;
private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckUserInput = CheckUserInput + e.Text;
if (CheckUserInput.ElementAt(0).ToString() == "*" && e.Text != "*")
{
e.Handled = false;
}
else if (CheckUserInput.ElementAt(0).ToString() == "*")
{
PrefixValidated = true;
e.Handled = true;
}
else
{
e.Handled = true;
}
}
Thanks to Dark Templar for helping with the discovery of this solution. Using PreviewTextInput and validating the character only if there are no other characters in the textbox seems to give the correct result.
Setting e.Handled = true stops the character from actually entering the textbox even for a second so the user is never aware of the prefix.
Code:
private void UserInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//if this is the first character entered, the textbox is not yet populated
//only perform validation if the character is a prefix
if (UserInput.Text != "")
return;
char CharAscii = (char)ScannerPrefix;
if (e.Text == CharAscii.ToString())
{
PrefixValidated = true;
e.Handled = true;
}
}

How can I make a TextBox accepts only numeric values?

I would like to know if there is a proper way for a textbox to accept only numbers.
For example, I want it to "stop" the user from filling it with "abcd1234" and only let him fill with "1234".
I tried following code and worked fine for me. The textbox will allow user to enter numbers only.
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
you can also try this
e.Handled = !(char.IsDigit(e.KeyChar));
You can evaluate the input using the following lines of code:
if (txtNumericBox.Text.All(char.IsDigit))
// Proceed
else
// Show error
If you define this as a string property with getter and setter then you can use like the following:
private string _MyNemericStringr;
public string MyNemericString
{
get { return _MyNemericStringr; }
set {
if (value.All(char.IsDigit))
_MyNemericStringr = value;
else
_MyNemericStringr = "0";
}
}
In the second example, if you assign any non-digit value to the property then it will return the value as "0". otherwise it will process as usual.
you can try this simple code.
private void keypressbarcode(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
it only accept numeric values and Backspace

How to make TextBox handle text like a hyperterminal in c#?

When the user enters a character with the TextBox in focus, I do not want the character to show up on the TextBox at all and I don't want to use the Clear() method as there may be other text in the TextBox I don't want erased. so far I've tried:
private void WriteBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key pressed
{
WriteBox1.Text = "";
}
// Code to write Serial....
String writeValues = WriteBox1.Text;
String withoutLast = writeValues.Substring(0, 1);
WriteBox1.Text = withoutLast;
}
This leaves the last letter entered in writeBox1. I need it to delete all characters entered.
I've also tired:
writeValues.Replace(writeValues, "");
WriteBox1.Text = writeValues;
Try setting Handled property on eventargs. Set Handled to true to cancel the KeyPress event. This keeps the control from processing the key press.
example :
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
https://msdn.microsoft.com/ru-ru/library/system.windows.forms.keypresseventargs.handled%28v=vs.110%29.aspx

How to stop the first character in a text box from being space?

I have a textbox and want user can not enter space in first textbox.the user can enter space in any where textbox apart of Beginning textbox.my computer = allow my computer = not allow (space in begining) , space maybe one or two or more.
If you really insist on doing this using one of the Events I would suggest you do it in the Text_Changed Event I have set you a simple way to do it..
private void txtaddgroup_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
if (textBox.Text.StartsWith(" "))
{
MessageBox.Show("Can not have spaces in the First Position");
}
}
Implement a keypress event where you get rid of any spaces, read more here.
Add this bit of code to your KeyDown event handler to stop the space key ever being registered:
//Check to see if the first character is a space
if (UsernameTextBox.SelectionStart == 0) //This is the first character
{
//Now check to see if the key pressed is a space
if (e.KeyValue == 32)
{
//Stop the key registering
e.Handled = true;
e.SuppressKeyPress = true;
}
}
32 if the Key Code for the space character.
You should call this function with parameter as 'e' on KeyPress event:
Here 32 is the ASCII value of space
void SpaceValidation(KeyPressEventArgs e)
{
if (e.KeyChar == 32 && ActiveControl.Text.Length == 0)
e.Handled = true;
}
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
SpaceValidation(e);
}

Having a MaskedTextBox only accept letters

Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "*[L]";
maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
}
How can I set it to accept only letters, but however many the user wants? Thanks!
This would be easy if masked text boxes accepted regular expression, but unfortunately they don't.
One (albeit not very pretty) way you could do it is to use the optional letter ? mask and put in the same amount as the maximum length you'll allow in the text box, i.e
maskedTextBox1.Mask = "????????????????????????????????.......";
Alternatively you could use your own validation instead of a mask and use a regular expression like so
void textbox1_Validating(object sender, CancelEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, #"^[a-zA-Z]+$"))
{
MessageBox.Show("Please enter letters only");
}
}
Or yet another way would be to ignore any key presses other than those from letters by handling the KeyPress event, which in my opinion would be the best way to go.
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"^[a-zA-Z]+$"))
e.Handled = true;
}
If you want only letters to be entered you can use this in keyPress event
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)) //The latter is for enabling control keys like CTRL and backspace
{
e.Handled = true;
}

Categories

Resources