Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธี Validate Email Address ใน C#

มี 2 วิธีหลัก:

1. ใช้ MailAddress (System.Net.Mail)

Simple แต่มีข้อจำกัด (เช่น ไม่เช็ค TLD อย่างเข้มงวด)

using System.Net.Mail;

string email = "hello@xyzcom";
try
{
    var mail = new MailAddress(email);
    bool isValid = mail.Host.Contains("."); // Basic check
    Console.WriteLine(isValid ? "Valid" : "Invalid");
}
catch
{
    Console.WriteLine("Invalid");
}

2. ใช้ Regex (System.Text.RegularExpressions)

แม่นยำกว่า ควบคุม Pattern เองได้

using System.Text.RegularExpressions;

string email = "hello@xyz.com";
string pattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

Regex regex = new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.Singleline);
bool isValid = regex.IsMatch(email);
// true

สรุป

  • MailAddress: เร็ว ใช้สำหรับ Validation พื้นฐาน
  • Regex: แม่นยำ ปรับ Pattern ได้ รองรับ RFC 5322 ได้เต็มที่ (แต่ Pattern จะซับซ้อน)