Regex, email validation taking user input from textbox - c#

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");
}

Related

how to make textbox numbers and operators only and in a valid form . . .

when I am entering input like this "12312.-.-.,," program is not working or giving any error
string c = textBox1.Text;
if (c.Contains(".") || c.Contains("-") || c.Contains("1") || c.Contains("2") || c.Contains("3") || c.Contains("4") || c.Contains("5") || c.Contains("6") || c.Contains("7") || c.Contains("8") || c.Contains("9") || c.Contains("0"))
{
if (c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1)
{
c = c.Substring(1, c.Length - 1);
if (c.Contains("-") || c.Contains("."))
{
MessageBox.Show("Error");
}
}
}
else { textBox1.Clear(); }```
You really should check input values with regular expressions:
Regex rgx = new Regex(#"^-?\d+(\.\d+)?$");
string test1 = "-123.23";
string test2 = "12312.-.-.,,";
if (!rgx.IsMatch(test1)) MessageBox.Show("Error in test1");
if (!rgx.IsMatch(test2)) MessageBox.Show("Error in test2");
The code doesnt enter your check for string to "not" start with '0' or end with '.' i assume?
if (!(c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1))

Is there a way to use a variable in a catch block that was previously assigned in a try block?

So I've just been making a basic little calculator made up of buttons and a textbox(tbxSum).
The problem I'm having is that if an invalid sum is input I want my catch block to pick it up(which it does) and replace what's in the textbox with the most recent result in the calculator(which it doesn't).
So say I say:
3+3=6
My calculator will now put 6 in the textbox for the next sum.
So then say I did:
6//3
It's invalid which the calculator picks up, but I want the textbox value to return to 6 from the previous sum.
This is what I've tried:
var myButton = (Button)sender;
if (myButton.Content.ToString() == "=")
{
DataTable dt = new DataTable();
string s = tbxSum.Text;
string result = "";
if (s.Contains("("))
{
s = s.Replace("(", "*(");
}
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
tbxSum.Text = v.ToString();
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
}
}
I also have a textblock(tbkSum) which shows the previous sum so I thought maybe I could take everything in there to the right of the equals sign but I have no idea how to do that.
class Calculate(){
private boolean lastGoodValueSet = false;
private int lastGoodValue = 0;
void buttonFunction(){
if (myButton.Content.ToString() == "=")
{
//Your code
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
lastGoodValue = v;
lastGoodValueSet = true;
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
if (lastGoodValueSet)
tbxSum.Text = lastGoodValue;
}
}
}
}
This is an example set of code you could use, it's a simple value that you have to store to say if a good computation has been done and if so, at the point of error we want to go back to the computation. Hope that helps! You'll want to put some kind of message to the user, so they know there was an error though.
We have to do this, as at the point of the user pressing the equals button, the value has already changed inside tbkSum, we need it before the user has changed the value, so the best time to grab it is at the point when we update the tbkSum text value at a successful calculation
This is also assuming you do not create a new instance of the Calculate class each time you do your computation. Otherwise you'd need to store the number somewhere else
EDIT
The other way to fix this issue is to instead prevent the duplicate in the first place, I read from your other comments that you control what goes into the text box by buttons on the application. Assuming all buttons go through the same method of buttonFunction() then you could do:
private char[] buttonChars = {'/','*', '+'/*e.t.c*/}
void buttonFunction(){
string buttonPressedStr = myButton.Content.ToString();
char buttonPressed = buttonPressedStr[0];
int pos = Array.IndexOf(buttonChars , buttonPressed);
if (pos > -1)
{
if (tbxSum.Text.Length > 0){
char last = tbxSum.Text[tbxSum.Text.Length - 1];
pos = Array.IndexOf(buttonChars , last);
}
else
pos = 0;
if (pos > -1){
tbkSum.Text += buttonPressedStr;
}
}
There are cleaner ways to do this, but it's an example of how you could have prevented your issue in the first place. Some explanation:
buttonChars is an array of your different button types that would be appended to your text in the box, an example is +, -, and so on
First it checks if the button pressed was in your collection of specified buttonChars
If so, we have to check what the last thing added to the tbxSum was
If the last thing added to tbxSum was again found in the buttonChars array, we don't want to append a string
Otherwise, if the tbxSum was empty or had another character at the end, we can append our character
You can store the old value in a variable declard outside the try block and use this variable in your catch block again:
string oldSumValue = tbxSum.Text;
try
{
// your code
}
catch
{
tbxSum.Text = oldSumValue ;
MessageBox.Show("Invalid Sum");
}
Alternatively I've come up with this to prevent there being:
A)Duplicate of '*' or '/'
B)Sum starting with '*' or '/'
public MainWindow()
{
InitializeComponent();
if (tbxSum.Text == "")
{
btnDiv.IsEnabled = false;
btnMult.IsEnabled = false;
}
}
protected void btnSumClick(object sender, EventArgs e)
{
btnDiv.IsEnabled = true;
btnMult.IsEnabled = true;
var myButton = (Button)sender;
int pos = tbxSum.Text.Length;
if (pos > 0)
{
if ((tbxSum.Text[pos - 1] == '/' || tbxSum.Text[pos - 1] == '*') &&
(myButton.Content.ToString() == "/" || myButton.Content.ToString() == "*"))
{
int location = tbxSum.Text.Length - 1;
tbxSum.Text = tbxSum.Text.Remove(location, 1);
}
}
}

Validating Textboxes and skipping Validations on form close

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.

How can I loop and check for correct user input in C#?

In this following main method I am trying to code so if the user does not input the proper response, then the code will loop until the user does provide the correct response.
I know I'm off center here, but I'm drawing a blank of how to correct this.
Please keep in mind I'm tying to keep this simple and basic.
public static void Main()
{
string name = "";
float startBal = 0;
int acctNum = 0;
string userInput = "";
float[] deposits = new float[30];
float[] withdrawls = new float[30];
DisplayIntroduction();
name = GetName();
startBal = GetStartBal();
acctNum = CreateAccount();
Console.WriteLine("\n{0}, here is your new account # {1}\n", name, acctNum);
do
{
Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
userInput = Convert.ToString(Console.ReadLine());
if (userInput.ToUpper() == "D")
{
//do the deposit, modify the deposit array
Console.WriteLine("You entered D");
}
else if (userInput.ToUpper() == "W")
{
//do the withdrawl, modify the withdrawl array
Console.WriteLine("You entered W");
}
else if (userInput.ToUpper() == "X")
{
//end the program, clear screen and display the summary
Console.WriteLine("You entered X");
}
else
{
Console.WriteLine("Please enter a valid option:");
}
} while (userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");
}
Common mistake, it should be some AND operators in your while, not OR.
while (userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X")
You want to loop if it's different than D AND different than W. Else it will always be true, since it cannot be D and W at the same time.
For example, if user inputs D, you get false true true, but you need a global result of false to leave the loop. With ANDs, you get a global result of false, while with OR you get true.
You can also use make it a little bit more compact (and less error-prone) with some LINQ (Works great for a lot of elements):
while(!new[] {"D", "W", "X"}.Contains(userInput));
It is not efficient to check twice a thing, you are checking user input in if-statements and again in the while-condition.
The simplest way is to set up a bool type variable to indicate whether user has entered the correct response or not.
bool flag = false;
do{
//your code
}
while(!flag)
and add this in every if-statement:
flag = true;
indicating that the user has inputed the correct value.
Pierre-Luc Pineault is correct.. But more logically it would be best to do..
while(!(userInput.ToUpper == "D" || userInput.ToUpper == "W" || userInput.ToUpper == "X"))
The "while" condition means the loop will keep triggering until the statement is false.
(userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");
Is going to be looping forever.
If the user enters "D" for instance
false OR true OR true
true
You'll want an & instead
(userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X");
If user enters a "D"
false AND true AND true
= false
(break out)
If user enters a "Z"
true and true and true
= true (remain in loop)
My version is something like this:
// While loop usually read better: keep on asking again and again until
// valid value is chosen
while (true) {
Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
String userInput = Console.ReadLine(); // <- You don't need any Convert here
// Try not use ".ToUpper" - move it to comparison: StringComparison.OrdinalIgnoreCase
if (String.Equals(userInput, "D", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'D'");
break;
}
else if (String.Equals(userInput, "W", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'W'");
break;
}
else if (String.Equals(userInput, "X", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'X'");
break;
}
Console.WriteLine();
Console.WriteLine("You've written an invalid option.");
}

How to check for end of string in textbox in c#

I am a noob, I am stuck on this code.
I am taking input from user in a textbox and saving it in a string. Then I want to run a loop until the string ends and I put if condition for different characters....
string que;
que = textBlock1.Text;
while (!que[i].Equals('\0'))
{
int res;
if (int.TryParse(que[i].ToString(), out res) || que[i].ToString() == "x" || que[i].ToString() == "/" || que[i].ToString() == "^")
{
f[j] = f[j] + que[i].ToString();
}
if (que[i].ToString() == "+" || que[i].ToString() == "-")
j++;
i++;
}
Can someone please guide me? What should I do??
Use:
textBlock1.Text.Lenght
That way you can know the length of the string.
Have you tried foreach(char c in que){ /*your code*/ } ?
If you want to just run through the loop until the end of the string, a simple condition like this should do:
int i = 0;
while (i < que.Length )
{
// Your code
}

Categories