Validating user entry on the fly causing some complications - c#

I wonder if there is better way of validating text box than using KeyDown event. The reason for this is that my event isn't reacting when it should. For example, in following code check works perfect. I can start typing characters and until 6 or more is entered I am being displayed that I must type at least 6 characters. The problem is that when I type 6 characters and then remove one, making it 5 characters; it doesn't display the error. Only when I remove more than 2 characters it display my error.
How can I avoid this, or what else I could use to do the check on the fly?
public AuthenticationWindow()
{
InitializeComponent();
// Setting up a password character.
// We are trying to hide what text user is typing.
txtPassword.PasswordChar = char.Parse("-");
txtPassword.MaxLength = 20;
txtUserName.MaxLength = 20;
txtPassword.KeyDown += KeyDownCheck;
}
protected void KeyDownCheck(object sender, KeyEventArgs e)
{
bool validPass = txtPassword.Text.Length < 6;
if (validPass)
lblMessage.Text = "Password can not be shorter than 6 characters!";
else
lblMessage.Text = "Password is valid.";
}

You should use the TextChanged event instead.
textBox1.TextChanged += new EventHandler(txtPassword_TextChanged);
private void txtPassword_TextChanged(object sender, EventArgs e) {
bool validPass = txtPassword.Text.Length < 6;
if (validPass)
lblMessage.Text = "Password can not be shorter than 6 characters!";
else
lblMessage.Text = "Password is valid.";
}

Related

get wrong textbox.TextLength in winforms

I am making a simple email sender and what I want to do is to check if the textbox.text has 14 characters. If it's 14 - then text turns to green, if less it turns to red. I've encountered a problem when I type 14th character. It doesn't turn green. It does when I type another character which is not shown since I have MaxLength = 14, but I still need to type in that 15th character. Also when I try deleting characters, the string doesn't turn red with the first deleted char, but after a few. I've tried things like Regex and trim() thinking that there might be some special characters but it doesn't seem to work. I also recorded a video with the issue to make it more describing.
private void trackBox1_KeyPress(object sender, KeyPressEventArgs e)
{
trackBox1.Text = RemoveSpecialCharacters(trackBox1.Text);
trackBox1.Text = trackBox1.Text.Replace("\r\n", "\n");
errorBox.Text = trackBox1.TextLength.ToString();
if (trackBox1.TextLength < 14)
{
trackBox1.ForeColor = Color.Red;
} else if (trackBox1.TextLength == 14)
{
trackBox1.ForeColor = Color.Green;
}
trackBox1.Text.TrimEnd();
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
Instead of using the trackBox1_Keypress put your if statement in the trackBox1_TextChanged event and to count the length of the text you should use trackbox.Text.Length instead of trackbox1.TextLength
Here is a sample snippet int the TextChanged event that changes the color from red to green if the text length is greater than or equal to 14.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length <= 14)
{
textBox1.ForeColor = Color.Red;
}
else
{
textBox1.ForeColor = Color.Green;
}
}
Im not sure if trackBox1.TextLength is the proper way to get the length
trackBox1.Text.Length //try this
//and also your event
private void yourTextBox_TextChanged(object sender, EventArgs e)
{
}
Have a look at the Control.KeyPress docs... the event fires after a key has been pressed, but before the character actually enters the textbox. This means that the length you're checking is one less than the length you were expecting (unless the key just pressed was backspace, which KeyPress also catches, in which case it is one greater than the length you were expecting).

Add character every 2 characters entered to textbox Windows Phone 8

Hi i want to make textbox to enter mac adress and every 2 characters i want to automaticly add ':'
I wanted to use TextChanged event
private void MacAdressTextBox_TextChanged(object sender, TextChangedEventArgs e) {
if (MacAdressTextBox.Text.Length > 2)
MacAdressTextBox.Text += ":";
}
here i am adding : after 2 characterrs entered but after those 2 characters the app frezes ... have no idea why any help?
When the text changes MacAdressTextBox_TextChanged is triggered.
In MacAdressTextBox_TextChanged you change the text.
see step 1
your text change causes an infinite recursion on MacAdressTextBox_TextChanged.
One way to do it would be to grab the Text, remove the colons, then add them back in at the correct positions. In order to keep the app from hanging in an endless recursive loop, you can add a variable to track whether or not the text is being changed by our code or the user.
For example:
// When this is true it means our code is changing the text
private bool updatingTextWithCode = false;
private void MacAdressTextBox_TextChanged(object sender, EventArgs e)
{
if (updatingTextWithCode)
{
// Our code is doing the update, so just reset the variable
updatingTextWithCode = false;
}
else
{
// The user is updating the text, so process the contents
var newText = "";
// Store the mac address without the ':' characters
var plainText = MacAdressTextBox.Text.Replace(":", "");
// Then add ':' characters in correct positions to 'newText'
for (int i = 1; i <= plainText.Length; i++)
{
newText += plainText[i - 1];
if (i % 2 == 0) newText += ":";
}
// Set our global variable and update the text
updatingTextWithCode = true;
MacAdressTextBox.Text = newText;
MacAdressTextBox.Select(MacAdressTextBox.TextLength, 0);
}
}
UPDATE: CodeCaster correctly pointed out that this code does not allow the user to backspace over a colon. One way to fix this is to add the following event handler as well:
private void MacAdressTextBox_KeyDown(object sender, KeyEventArgs e)
{
// Disable formatting code when backspacing
if (e.KeyCode == Keys.Back) { updatingTextWithCode = true; }
}

How to restrict user to TextBox if value entered is incorrect

In my program I have a TextBox who's value must be set in a specific integer range. If it is not within this range, it should warn the user and then highlight the incorrect text inside of the TextBox for re-editing (implying that the user must enter a value that is in the correct range before they are allowed to leave the TextBox). How would I change my code so that it performs these operations?
This is what I have so far. I am using a TextChanged event. This code warns the user about the restriction breach and refocuses (I would like to highlight the value instead) on the TextBox, but does not prevent the user from clicking out of it afterward:
int maxRevSpeed;
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ")
maxRevSpeed = 0;
else
{
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
maxRevSpeed_textBox.Focus();
}
}
Please note that this question is a revisit of a former question of mine. I am aware that it may be "frowned upon" to take this approach to a TextBox, but regardless I would still like to figure out how to implement such a thing. Thank you.
Update 1:
After looking at everyone's suggestions I have updated my code:
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ") //Is Empty or contains spaces
maxRevSpeed = 0;
else if (!Regex.IsMatch(maxRevSpeed_textBox.Text, #"^[\p{N}]+$")) //Contains characters
maxRevSpeed = 0;
else
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
}
//Max Rev Speed -- Lost Focus
private void maxRevSpeed_LostFocus(object sender, RoutedEventArgs e)
{
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
//Supposed to highlight incorrect text -- DOES NOT WORK
maxRevSpeed_textBox.SelectionStart = 0;
maxRevSpeed_textBox.SelectionLength = maxRevSpeed_textBox.Text.Length;
}
}
The integer representing the text in the textBox is now dealt with in the textChanged event. The LostFocus event handles the warning and the re-selection of the incorrect text value. However, the highlight text method works when it is in the textChanged event, but not in it's current location. Why is that, and how can I fix it?
If you just want to stop focus from leaving a TextBox, all you need to do is to set the Handled property of the KeyboardFocusChangedEventArgs object to true in a PreviewLostKeyboardFocus handler when your invalid condition is true:
private void PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
e.Handled = IsInvalidValue;
}
This of course assumes that you have a property named IsInvalidValue that you set to true when the entered data is invalid and false otherwise.
You can prevent the user from entering the text or out of range by using PreviewTextInput handler of textbox, call it like this.
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
e.Handled = true;
}
}
The code above is for entering numbers only, you can change it according to your requirements, hope it helps :)
Hi I suppose you are using C#, here you can find a relevant post: C# auto highlight text in a textbox control
As they stated the following code should select the text inside texbox
In Windows Forms and WPF:
maxRevSpeed_textBox.SelectionStart = 0;
maxRevSpeed_textBox.SelectionLength = textbox.Text.Length;

Disable OK button when text in text box is no longer correct format in C# Form

This seems like it should be easy to solve, but my head is fried and I can't think of a good way to do this! Basically, I have a form with details on it. A user can click a button to pick a new PIN number. On this form, I have some Regex to ensure that the value entered in the textbox is a number and is greater than 4 digits.
Code for this:
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"[0-9]{4,}";
Regex regex = new Regex(pattern);
if (regex.IsMatch(textBoxPin.Text))
{
buttonOK.Enabled = true;
}
};
Now, OK becomes enabled if the PIN is more then 4 digits, but if you use backspace and end up with no digits, it doesn't matter - OK is still enabled from before. Is there any way that I can re-disable the button?
At the moment, I have an event from when OK is clicked and it's less than 4 - it pops up a warning message, as code illustrates below:
private void buttonOK_Click(object sender, EventArgs e)
{
if (textBoxPin.Text.Length < 4)
{
DialogResult dr = MessageBox.Show("PIN must be at least 4 digits!", "Important Message", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
if (dr == DialogResult.Cancel)
{
}
else if (dr == DialogResult.Retry)
{
}
}
}
but with this way, I'm not sure how to revert the changes, as there are a lot of different things interacting in the bigger project that I'd need (basically, if it was cancel, I want to not save the changes etc.). This is why I think it would be easier if I could just re-disable the button if it was no longer correct. Is there any way of doing this?
Also, if I do press backspace, I'm then able to enter letters too, which shouldn't be allowed. I tried messing with Keypresses but I thought regex would be neater.
Any advice would be greatly appreciated!
if (regex.IsMatch(textBoxPin.Text))
{
buttonOK.Enabled = true;
}
else
{
buttonOK.Enabled = false;
}
Would that not work?
Shortened:
buttonOk.Enabled = regex.IsMatch(textBoxPin.Text)
Did you try:
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"[0-9]{4,}";
Regex regex = new Regex(pattern);
if (regex.IsMatch(textBoxPin.Text))
{
buttonOK.Enabled = true;
}
else
{
buttonOK.Enabled = false;
}
};
?

How do I make a error message appear when a number is types in?

I have set the text box so that only letters can be entered and I would like to know how I can make a error message appear when anything other than a letter is entered. The following is my code:
private void FirstName_KeyPress_1(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < 65 || e.KeyChar > 122)
{
e.Handled = true;
}
}
private void FirstName_TextChanged_1(object sender, EventArgs e)
{
FirstName.KeyPress += new KeyPressEventHandler(FirstName_KeyPress_1);
}
I have also tried
if (e.KeyChar < 65 || e.KeyChar > 122)
{
e.Handled = true;
}
else
{
MessageBox.Show (" Please enter a letter",
"Error Message");
}
But this message appears once a letter is typed after a number and does not go when "ok" is clicked. It appear about 4 times until it disappears.
Could anyone help me with this please?
Thank you
The problem is your placement of this logic. If you want the message to appear when the user clicks the ok/submit button you need to perform a check there and display the message. Your example is checking (and therefor potentially displaying the error message) after every input.
So you want something like;
// generate this stub by double clicking the ok/submit button in the GUI builder
private void FirstName_EnterButtonClicked(object sender, EventArgs e)
{
char[] chars = FirstNameTextBox.Text.ToCharArray();
bool good = true;
int placeholder;
for (int i = 0; i < chars.length; i++)
{
if (int.TryParse(chars[i], placeholder)
{
good = false;
break;
}
}
if (!good)
MessageBox.Show("Names cannot contain numbers.");
}
A quick explanation of the code - Firstly, we're waiting til the user tries to submit the full input before validating it rather than after each character is added. At this point we convert the input string to a character array and loop over it. TryParse returns true if the input is an integer and sets placeholder's value to that integer. If the user has entered an int we go into that if where we change our flag to false then we break since there's no need to continue checking the rest of the string. Outside of the loop we do the MessageBox.Show.
I prefer to use javascript to implement these kindof of functionalities
function isAlphabet(e) {
var keynum
var keychar
var numcheck
if (e.keyCode >= 91 && e.keyCode <= 96)
return false;
keynum = e.keyCode
keychar = String.fromCharCode(keynum)
numcheck = /[a-zA-z ]/
return e.returnValue = numcheck.test(keychar);
}
You can call the following function Onclientclick event of the submit button.
Hope this helps :)
if you want to use Linq and get a count of Items that are invalid in a List
do the following
string vStr = FirstNameTextBox.Text;
var isValid = (from tmp in vStr
where char.IsDigit(tmp)
select tmp).ToList();
you can do a
ShowMessage(string.Join(",",isValid));
yields 2,3,3,3 in a MessageBox

Categories