Listen
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.Write("Enter your email address: "); string email = Console.ReadLine(); List<string> errors = new List<string>(); if (string.IsNullOrWhiteSpace(name)) { errors.Add("Name is required."); } if (string.IsNullOrWhiteSpace(email)) { errors.Add("Email address is required."); } else if (!IsValidEmail(email)) { errors.Add("Invalid email address."); } if (errors.Count > 0) { Console.WriteLine("The following errors occurred:"); foreach (string error in errors) { Console.WriteLine("- " + error); } } else { Console.WriteLine("Name: " + name); Console.WriteLine("Email address: " + email); } } static bool IsValidEmail(string email) { try { var addr = new System.Net.Mail.MailAddress(email); return addr.Address == email; } catch { return false; } } }This example is an ASP.NET page with a form containing three text boxes (for first name, last name, and email) and a submit button. The following steps are performed:
- The
Page_Load
method is executed when the page loads.- When the submit button is clicked, the
SubmitButton_Click
method is executed.- The input values are read from the text boxes and trimmed using
string.Trim()
.- Validation is performed to ensure that all fields are filled in using
string.IsNullOrEmpty()
. If validation fails, an error message is displayed using aLabel
control and the method returns using thereturn
keyword.- Validation is performed to ensure that the email address is valid using a custom
IsValidEmail()
method. If validation fails, an error message is displayed using aLabel
control and the method returns using thereturn
keyword.- If validation passes, the form data is considered valid and can be processed in the remaining code.