Reputation: 308
Here Is My C# code:
private void btnLogin_Click(object sender, EventArgs e)
{
if (Regex.IsMatch(txtPassword.Text, @"(!|@|#)"))
{
MessageBox.Show("Password Must Contain at least a special character");
}
else
{
SqlConnection con = new SqlConnection("Data Source=Sumit;Initial Catalog=BroadDB;Integrated Security=True");
string sql = "select * from tblLogin where username=@username and password=@password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@username", txtUsername.Text);
cmd.Parameters.AddWithValue("@password", txtPassword.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Form2 obj = new Form2();
obj.Show();
}
else
{
MessageBox.Show("Invalid Data");
}
}
}
How to validate that password should contain atleast a number and a special character when login button is clicked.
Upvotes: 2
Views: 2349
Reputation: 23
Sorry, I can't comment yet, but don't you use a regex for special chars already?
if (Regex.IsMatch(txtPassword.Text, @"(!|@|#)"))
{
MessageBox.Show("Password Must Contain at least a special character");
}
If I understand your question right you could do this also with numbers or letters.
Have a look on this answered question, it could help you:
How to check if a String contains any letter from a to z?
It's because you don't use a -> ! before Regex.IsMatch, so the MessageBox only Appears when the user inputs a special char, but not when he don't do it.
Try it with this one:
if (!Regex.IsMatch(txtPassword.Text, @"(!|@|#)"))
{
MessageBox.Show("Password Must Contain at least a special character");
}
Upvotes: 0
Reputation: 1605
try below code
if (!Regex.IsMatch(txtPassword.Text, @"(!|@|#)") || !txtPassword.Text.Any(char.IsDigit))
{
Console.WriteLine("Password Must Contain at least a special character and digit");
}
else
{
// DO YOUR STUFF
}
Upvotes: 1
Reputation: 1396
You can achieve this by testing the string you retrieve from the user input. For this you can best use a regex
.
Regex regexPassword = new Regex( @"
^ // From the start of the string
[a-zA-Z0-9!@#]+ // The string should contain some of these characters, like letters including digits and special chars
(<=[!@#]) // one of these should be a special character
(<=[0-9]) // one of these should be a number
$ // end of string
" , RegexOptions.IgnorePatternWhitespace ) ;
Then of course you can test your regex against your string as usual:
if(regexPassword.IsMatch(yourPasswordString))
{
//Do what you want
}
Upvotes: 0