Validating User Input
Program.cs
123456789101112131415161718192021222324using System; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Console.Write("Enter your age: "); string input = Console.ReadLine(); int age; if (!int.TryParse(input, out age) || age <= 0) { Console.WriteLine("Invalid input. Age must be a positive integer."); } else { Console.WriteLine($"Your age is: {age}"); } } } }
ValidationExamples.cs
123456789101112131415161718192021222324// This file is for illustration only and is not meant to be run directly. using System.Text.RegularExpressions; public class ValidationExamples { // Email format validation public bool IsValidEmail(string email) { // Simple pattern for demonstration; real validation may require more checks return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); } // Password strength validation public bool IsStrongPassword(string password) { // At least 8 characters, one uppercase, one lowercase, one digit return password.Length >= 8 && Regex.IsMatch(password, @"[A-Z]") && Regex.IsMatch(password, @"[a-z]") && Regex.IsMatch(password, @"\d"); } }
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 1
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Suggested prompts:
Can you explain how the regular expression for email validation works?
What are some common mistakes to avoid when validating passwords?
Can you show more examples of input validation in C#?
Fantastisk!
Completion rate forbedret til 4.17
Validating User Input
Sveip for å vise menyen
Program.cs
123456789101112131415161718192021222324using System; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Console.Write("Enter your age: "); string input = Console.ReadLine(); int age; if (!int.TryParse(input, out age) || age <= 0) { Console.WriteLine("Invalid input. Age must be a positive integer."); } else { Console.WriteLine($"Your age is: {age}"); } } } }
ValidationExamples.cs
123456789101112131415161718192021222324// This file is for illustration only and is not meant to be run directly. using System.Text.RegularExpressions; public class ValidationExamples { // Email format validation public bool IsValidEmail(string email) { // Simple pattern for demonstration; real validation may require more checks return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); } // Password strength validation public bool IsStrongPassword(string password) { // At least 8 characters, one uppercase, one lowercase, one digit return password.Length >= 8 && Regex.IsMatch(password, @"[A-Z]") && Regex.IsMatch(password, @"[a-z]") && Regex.IsMatch(password, @"\d"); } }
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 1