Validating Textboxes and skipping Validations on form close - c#

Following is the code snippet that I am using to validate my textboxes.
C# Code
private void TxtEmail_Validating(object sender, CancelEventArgs e)
{
string StrEmail = TxtEmail.Text.Trim();
if (StrEmail == "" || StrEmail.IndexOf("") > 0 || StrEmail.IndexOf('"') > 0 || StrEmail == " " || StrEmail.IndexOf(" ") > 0)
{
MessageBox.Show("Email Cannot be Left Blank");
TxtEmail.Select();
}
Regex r = new Regex(#"#.");
if (r.IsMatch(TxtEmail.Text))
{
AutoValidate = AutoValidate.Disable;
}
else
{
MessageBox.Show("Invalid Email Format");
TxtEmail.Clear();
TxtEmail.Focus();
}
}
private void TxtPassword_Validated(object sender, EventArgs e)
{
string StrPass=TxtPassword.Text;
if (StrPass == "" || StrPass.IndexOf("") > 0 || StrPass.IndexOf('"') > 0 || StrPass == " " || StrPass.IndexOf(" ") > 0)
{
MessageBox.Show("Invalid Password");
TxtPassword.Focus();
}
Regex r = new Regex(#"##");
if (r.IsMatch(TxtPassword.Text))
{
AutoValidate = AutoValidate.Disable;
}
else
{
MessageBox.Show("Invalid Password");
TxtPassword.Clear();
TxtPassword.Focus();
}
}
I am using AutoValidate feature to cancel validation if the parameters within the Regex match.But the problem is when I use AutoValidate or Set CauseValidation to false,the validation of TextBox is done the first time the form is loaded. But when I remove the text within the texbox and re-enter it, validation doesn't work the 2nd time and does not throw the message "Invalid Email"
In the case of Password Validation.Even after entering password as per the parameters within the Regex,it throws "Invalid Password" message.I saw questions here based on validation but none of them have satisfactory solution to my question.
Can anyone help me to rectify this error? I want to achieve Validation without ErrorProvider which is another option.

Related

textbox text is checked only once

I have 2 panels. If textboxes are empty, there is a message. My problem is, say I get to second panel then go back and delete texts then go to second panel again, it does not show message. Is there a way to check the texts every time?
private void bttn_Next_Click(object sender, EventArgs e)
{
if (txt_FirstName.Text == " " || txt_LastName.Text == " " ||
txt_Email.Text == " " || txt_Contact.Text == " " ||
txt_HouseNumber.Text == " " || txt_Street.Text == " " ||
txt_Barangay.Text == " " || txt_Municipality.Text == "")
{
MessageBox.Show("Please complete all required fields.", "Message");
}
else
{
panel1.Hide();
panel2.Hide();
panel3.Show();
}
}
The correct way to check for empty string is as follows
private void bttn_Next_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txt_FirstName.Text) || string.IsNullOrWhiteSpace(txt_LastName.Text) ||
string.IsNullOrWhiteSpace(txt_Email.Text) || string.IsNullOrWhiteSpace(txt_Contact.Text) ||
string.IsNullOrWhiteSpace(txt_HouseNumber.Text) || string.IsNullOrWhiteSpace(txt_Street.Text) ||
string.IsNullOrWhiteSpace(txt_Barangay.Text) || string.IsNullOrWhiteSpace(txt_Municipality.Text))
{
MessageBox.Show("Please complete all required fields.", "Message");
}
else
{
panel1.Hide();
panel2.Hide();
panel3.Show();
}
}

C# Character count condition

how can i put condition here. Like if i Inputted a 4 digit character, it'll put a Prefix which is "F-".
try
{
Service1 ws = new Service1();
if (e.KeyChar == (char)13 && button1.Enabled == true)
{
inputtxt = F.Text.ToString();
showpic(inputtxt);
if (ws.VerifyEID(inputtxt) == false)
{
MessageBox.Show("You have entered an incorrect Employee ID. Please try again!", "Attendance Monitoring System", MessageBoxButtons.OK, MessageBoxIcon.Warning);
F.Text = null;
}
else
{
panel1.Visible = false;
SqlToText(inputtxt);
ShowOffset(inputtxt);
if (BtnTimeIn.Visible == true)
{
BtnTimeIn.Focus();
}
else
{
BtnTimeOut.Focus();
}
}
}
Help me please, thankyou.
You can insert this in your code:
inputtxt = inputtxt.StartsWith("F-") ? inputtxt : "F-" + inputtxt;
But I would personally have that prefix on the textbox to make it clear for the users what to type in and have them type less characters.

Regex, email validation taking user input from textbox

I am just trying to validate a users input using a textbox, the validation works i think. However, it is only allowing me to type one character at a time. I'm not sure how to check one char at a time until they have entered a full email address.
I think this is checking every-time when a char is entered which will result in failure until it is copy and pasted in.
string strRegex = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
Regex re = new Regex(strRegex);
if (re.IsMatch(txtEmail.Text) || txtEmail.Text == "" || txtEmail.Text.Length > 100 && txtEmail.Text.Length < 10)
{
MessageBox.Show("Thanks");
}
else
{
MessageBox.Show("Please enter a valid email address");
}
}
May be you are validating on keyup, keydown event. Validate on change event.
If you are doing in winform application you can do that on focusleave event
#Tetsuya Yamamoto this is what i have so far, but im not sure if this is what you mean
string strRegex = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
Regex re = new Regex(strRegex);
if (re.IsMatch(txtEmail.Text) || txtEmail.Text == "" || txtEmail.Text.Length > 100 && txtEmail.Text.Length < 10)
{
try
{
var email = new MailAddress(strRegex);
MessageBox.Show("Thanks");
}
catch (FormatException)
{
MessageBox.Show("Wrong");
}

how to allow user to enter the password 3 times in c#?

I'm working in this program for 3 hours but i do not know where I'm doing wrong .If you could help i really appreciate it . The problem is when i'm entering the password .It says it is wrong password even if i put the right password it does not allows me to retry again .The program suppose to allows the user to try 3 times if the users puts wrong password after third time the program has to close .
public partial class UserAndPin : Window
{
public UserAndPin()
{
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
try
{
StreamReader sr = new StreamReader("Customer.txt");
short attempts = 0;
string line;
while ((line = sr.ReadLine()) != null)
{
string[] lineArray = line.Split(';');
if (lineArray[0] == txtName.Text & lineArray[1] == pbPassword.Password)
{
MainWindow mainWindow = new MainWindow();
this.Hide();
mainWindow.ShowDialog();
//return;
}
else
{
attempts++;
if (attempts < 3)
{
MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");
}
if (attempts == 3)
{
MessageBox.Show("Please try again later");
this.Close();
}
}
}
sr.Close();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}
}
Since you are declaring the short attempts = 0; inside the btnOK_Click everytime you click the button will initiate the attempts to be 0 whereas you want it to be increased by 1 everytime the user clicks the button thus you need to declare it globally like
public partial class UserAndPin : Window
{
short attempts;
public UserAndPin()
{
InitializeComponent();
attempts = 0;
}
attempts++; should be below the while loop because if you have 10 user info in the file it will add or increment the attempt every time the condition doesnt match.
Now if the username and password doesnt match from the file you are reading. which obviously doesnt match if the user info is at 10th position or line it will give you message box for 9 times. Another issue is Logical AND operator it is && and not & and than it would match so the correct way should be
public partial class UserAndPin : Window
{
short attempts;
public UserAndPin()
{
InitializeComponent();
attempts = 0;
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
try
{
StreamReader sr = new StreamReader("Customer.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
string[] lineArray = line.Split(';');
if (lineArray[0] == txtName.Text && lineArray[1] == pbPassword.Password)
{
MainWindow mainWindow = new MainWindow();
this.Hide();
mainWindow.ShowDialog();
//return;
}
}
sr.Close();
if (attempts < 3)
{
MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");
}
else
{
MessageBox.Show("Please try again later");
this.Close();
}
attempts++; //Since user has attempted it.
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}
You should initilize the 'attempts ' every authentication successfully. Or more than 3 times in 3 hours.
If you login in success at 2 times then the 'attempts' should be 0.
If the project rejects you log in over than 3 hours, the 'attempts' also should be set to 0.
First you need to read your file to get all user name and password. Ideally, you would do this only once in the constructor.
Then, you need to increment your counter by one. And this counter needs to be declared outside the click event handler like stated in other answers.
Finally, you can then check if the user/password entered match one from the file. if it does, you can open your form. If not, you show one of the message box depending if the user has reached the third attempt or not.
public partial class UserAndPin : Window
{
short attempts;
public UserAndPin()
{
InitializeComponent();
attempts = 0;
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
try
{
var users = File.ReadAllLines("Customer.txt")
.Select(line => new { login = line[0], password = line[1] })
.ToList();
attempts++;
if (users.Any(user => user.login == txtName.Text && user.password == pbPassword.Password))
{
MainWindow mainWindow = new MainWindow();
this.Hide();
mainWindow.ShowDialog();
return;
}
else
{
if (attempts < 3)
{
MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");
}
if (attempts >= 3)
{
MessageBox.Show("Please try again later");
this.Close();
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}
Dictionary<string, string> loginInfo;
short attempts = 0;
public UserAndPin()
{
InitializeComponent();
// Load the file to the dictionary
loginInfo = File.ReadAllLines("Customer.txt")
.Select(i => i.Split(';')) // Lines format: Username;Password
.ToDictionary(i => i[0].ToLower(), i => i[1]); // Username is the key of the dictionary
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
var userId = txtName.Text.ToLower(); // Username ignore case
var password = pbPassword.Password;
if (loginInfo.ContainsKey(userId) && loginInfo[userId] == password)
{
// login success, show main window
MainWindow mainWindow = new MainWindow();
this.Hide();
mainWindow.ShowDialog();
return;
}
// login fail, increment the count only
attempt++;
if (attempts < 3)
{
MessageBox.Show("The NAME or PIN is incorect, you have " + (3 - attempts) + " attemps more");
}
if (attempts == 3)
{
MessageBox.Show("Please try again later");
this.Close();
}
}

Button not working on an != if statement

I'm trying to replicate the Mastermind game within c# and have hit a hurdle, so to speak. The problem I'm facing is at the stage where player 2 guesses which 3 checkboxes are correct from the 6 available. (8 rows for 8 attempts/lives at guessing). The code I have works when player 2 guesses the correct checkboxes, however when the incorrect checkboxes are selected and the "guess" button is clicked nothing happens. I have a second if statement to check this but obviously something must be wrong. The code for the button click event is:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
CheckBox[] checkBoxArray = new CheckBox[]
{ checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
for (int i = 0; i < checkBoxArray.Length; i++)
{
if (checkBoxArray[i].Checked)
boxesChecked++;
}
if (boxesChecked > 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Only 3 are allowed.");
else if (boxesChecked < 3)
MessageBox.Show("You have checked " + boxesChecked.ToString() +
" checkboxes. Please choose 3.");
if (checkBox1.Checked == cb1)
if (checkBox2.Checked == cb2)
if (checkBox3.Checked == cb3)
if (checkBox4.Checked == cb4)
if (checkBox5.Checked == cb5)
if (checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!",
"Game Won");
if (MessageBox.Show("Would you like to play again?",
"Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
if (checkBox1.Checked != cb1)
if (checkBox2.Checked != cb2)
if (checkBox3.Checked != cb3)
if (checkBox4.Checked != cb4)
if (checkBox5.Checked != cb5)
if (checkBox6.Checked != cb6)
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
}
}
Ok, let's go. There a few things to review at your code:
1. How many checkbox are checked?
Let's use a little lamba to make that for a little bit prettier:
boxesChecked = checkBoxArray.Where<CheckBox>(x => x.Checked).Count();
2. If the user doesn't have checked 3 checkboxes, let's show the message and leave the method!
It's a little bit simplified too, you may wish to change it:
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
3. Verify the result
Let's change those if a little bit. Notice the main else condition (player lost!):
if (checkBox1.Checked == cb1
&& checkBox2.Checked == cb2
&& checkBox3.Checked == cb3
&& checkBox4.Checked == cb4
&& checkBox5.Checked == cb5
&& checkBox6.Checked == cb6)
{
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
else
{
MessageBox.Show("Unlucky, Guess Again!");
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
checkBox4.Visible = false;
checkBox5.Visible = false;
checkBox6.Visible = false;
}
Please note that I'm not saying that this is the best design for a game, I'm just pointing out a few things to change on your code.
UPDATE
Based on spender's comment, let's review your method. Please, check it out:
private void Guess_button_Click(object sender, EventArgs e)
{
int boxesChecked = 0; // Default value
List<CheckBox> AllTheCheckBoxes = new List<CheckBox> { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6 };
boxesChecked = AllTheCheckBoxes.Where<CheckBox>(x => x.Checked).Count();
if (boxesChecked != 3)
{
MessageBox.Show(string.Format("You have checked {0} checkboxes. Please choose 3.", boxesChecked));
return;
}
if (AllTheCheckBoxes.Any<CheckBox>(x => x.Checked != Convert.ToBoolean(x.Tag)))
{
MessageBox.Show("Unlucky, Guess Again!");
AllTheCheckBoxes.ForEach(x => x.Visible = false);
return;
}
MessageBox.Show("Congratulations, You Win!", "Game Won"); // Display MessageBox
if (MessageBox.Show("Would you like to play again?", "Play Again?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
p1input restart = new p1input();
this.Close(); // Close current window
restart.Show(); // Open restart (instance of p1input)
}
else
{
Environment.Exit(0); // Terminate Application
}
}
Notice that I'm using the Tag property. It's an arbitrary string, that developer may use for any purpose. Here I'm expecting that the correct value (true or false) is stored at this property.
UPDATE 2
Regarding OP comment about finding all the checkboxes (looks like its 48 total).
You can use the following statement (understand it and improve it to your needs).
List<CheckBox> AllTheCheckBoxes = this.Controls.AsQueryable().OfType<CheckBox>().Where(x => x.Tag != null).ToList();
Your check for an incorrect value appears to be inside the braces of the if statements for when the user guesses correctly.
In other words, it won't ever be hit. You need to break it out of the braces so it runs.
Like others said, all those nested ifs are going to hurt you in the end. Consider cleaning up that bit so you can understand what's happening better.

Categories