form validation in csharp

Form validation in C# can be implemented using various techniques such as regular expressions, conditional statements, and event handlers. The following code snippet illustrates a simple form validation scenario that checks if the user has entered a valid email address before submitting the form.

main.cs
private void submitButton_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(emailTextBox.Text))
    {
        MessageBox.Show("Please enter your email address.", "Error");
        return;
    }
    
    // Validate email address
    string pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
    Match match = Regex.Match(emailTextBox.Text, pattern, RegexOptions.IgnoreCase);

    if (!match.Success)
    {
        MessageBox.Show("Please enter a valid email address.", "Error");
        return;
    }

    // Form submission logic goes here...
}
551 chars
21 lines

In the above code, we first check if the email address input field is empty. If so, we display an error message using MessageBox.Show() and return from the method without submitting the form. If the input field is not empty, we use a regular expression pattern to validate the email address format. If the pattern does not match, we display an error message and return from the method. Finally, if the email address is valid, we can proceed with the form submission logic.

gistlibby LogSnag