I am currently creating a registration form and it contains error handling processes for the text boxes, like certain characters are only allowed in a certain textbox and so on. So for my first try I tried creating an algorithm that will check if the user only enters letters from the keyboard meaning no numbers and no signs (excluding the period sign) so here is my take on this matter:
private bool isInCorrectInput = false;
private void tBoxTitle_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(isInCorrectInput))
{
tBoxTitle.SelectAll();
errorProvider1.SetError(tBoxTitle, "This text box accepts letters and the '.' sign only as input, please try again.");
e.Handled = true;
}
}
private bool checkInputByKeyCode(Keys key)
{
if ((key >= Keys.Oem1) && (key <= Keys.Oem8) || ((key >= Keys.NumPad0) && (key <= Keys.NumPad9)) || ((key >= Keys.D0) && (key <= Keys.D9)) || (key == Keys.Divide) || (key == Keys.Multiply) || (key == Keys.Subtract) || (key == Keys.Add) || (key == Keys.Space))
{
return false;
}
else
{
return true;
}
}
YES i know it looks brute forced that's why I am asking you guys how could I optimize this code of mine here.
I don't know how to use regex. Although I know that regex will make my life easier. But its just that I came in late for our class and the only way I could make up for my deduction for this activity is to create an error handling process without the use of regex (to impress the professor I guess).
And in this part:
(key >= Keys.Oem1) && (key <= Keys.Oem8)
I just took a wild guess by thinking that this will stop all input of symbols, but it turns out because of this my control of the . symbol just above the alt key on your keyboard has been disabled :(
I am also having trouble with asking for the email of the user. My take on that matter looks something like this:
if (!((tBoxEmail.Text.Contains(".")) && (tBoxEmail.Text.Contains("@"))))
{
errorProvider1.SetError(tBoxEmail, "ERROR!");
}
only problem with that is when the user types in just @. the program still accepts it, so the only way I could counter that was to check if the length of tboxEmail.text was greater than 2, although it presents problems in the latter part of the string. One example of those problems is if the user enters a string of chars and just inserts @. at the end it still accepts it, or maybe if he decides to type in emai@provider. the program will still accept it.
I decided to use keydown and keypress so that I may catch the incorrect input prior to letting the user submit it to the database.
And how do I remove the errorprovider once the user enters correct input? for example they get it wrong and the error provider fires then if the user finally inputs the correct input the fired error provider does not go away.
Sorry for asking too much.