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

ตรวจสอบความถูกต้องของ Password ใน C#

ภาพรวม

สร้าง Password Validator ตรวจสอบเงื่อนไข: ความยาว, ตัวพิมพ์ใหญ่/เล็ก, ตัวเลข, สัญลักษณ์พิเศษ, ไม่มี whitespace

โค้ดตัวอย่าง: Password Validator Class


using System;
using System.Text.RegularExpressions;

public class PasswordValidator {
    public static ValidationResult Validate(string password) {
        var errors = new List<string>();

        if (string.IsNullOrWhiteSpace(password)) {
            return new ValidationResult(false, new[] { "Password cannot be empty" });
        }

        // 1. Length: 8-14 characters
        if (password.Length < 8 || password.Length > 14) {
            errors.Add("Password must be 8-14 characters long");
        }

        // 2. At least one uppercase
        if (!password.Any(char.IsUpper)) {
            errors.Add("Password must contain at least one uppercase letter");
        }

        // 3. At least one lowercase
        if (!password.Any(char.IsLower)) {
            errors.Add("Password must contain at least one lowercase letter");
        }

        // 4. At least one digit
        if (!password.Any(char.IsDigit)) {
            errors.Add("Password must contain at least one digit");
        }

        // 5. At least one special character
        string specialChars = @"!@#$%^&*()_+-=[]{}|;':"",<>.?/`~";
        if (!password.Any(c => specialChars.Contains(c))) {
            errors.Add("Password must contain at least one special character");
        }

        // 6. No whitespace
        if (password.Any(char.IsWhiteSpace)) {
            errors.Add("Password cannot contain whitespace");
        }

        return new ValidationResult(errors.Count == 0, errors);
    }
}

public class ValidationResult {
    public bool IsValid { get; }
    public IReadOnlyList<string> Errors { get; }

    public ValidationResult(bool isValid, IEnumerable<string> errors) {
        IsValid = isValid;
        Errors = errors.ToList().AsReadOnly();
    }
}

การใช้งาน


string[] testPasswords = {
    "weak",
    "StrongPass123",
    "StrongPass123!",
    "VeryLongPasswordThatExceedsFourteenCharacters!",
    "NoSpecialChar123",
    "Has Space 123!"
};

foreach (string pwd in testPasswords) {
    var result = PasswordValidator.Validate(pwd);
    Console.WriteLine($"'{pwd}': {(result.IsValid ? "VALID" : "INVALID")}");
    if (!result.IsValid) {
        foreach (string error in result.Errors) {
            Console.WriteLine($"  - {error}");
        }
    }
}

ผลลัพธ์ตัวอย่าง


'weak': INVALID
  - Password must be 8-14 characters long
  - Password must contain at least one uppercase letter
  - Password must contain at least one digit
  - Password must contain at least one special character
'StrongPass123': INVALID
  - Password must contain at least one special character
'StrongPass123!': VALID
'VeryLongPasswordThatExceedsFourteenCharacters!': INVALID
  - Password must be 8-14 characters long
'NoSpecialChar123': INVALID
  - Password must contain at least one special character
'Has Space 123!': INVALID
  - Password cannot contain whitespace

Regex Version (Single Pattern)


public static class PasswordRegex {
    // ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,14}$
    private static readonly Regex _pattern = new Regex(
        @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,14}$",
        RegexOptions.Compiled
    );

    public static bool IsValid(string password) => _pattern.IsMatch(password);
}

Regex Pattern Breakdown

PartMeaning
^Start of string
(?=.*[a-z])Lookahead: มี lowercase อย่างน้อย 1 ตัว
(?=.*[A-Z])Lookahead: มี uppercase อย่างน้อย 1 ตัว
(?=.*\d)Lookahead: มี digit อย่างน้อย 1 ตัว
(?=.*[!@#$%^&*])Lookahead: มี special char อย่างน้อย 1 ตัว
.{8,14}ความยาว 8-14 ตัวอักษร
$End of string

แนวทางปฏิบัติที่ดี (NIST Guidelines)

  • ไม่จำกัดความยาวสูงสุด (หรือสูงสุด 64+ characters)
  • อนุญาตให้ใช้ whitespace ได้ (passphrase)
  • ตรวจสอบ Blacklist (common passwords, breached passwords)
  • ไม่บังคับ Complexity rules ที่ซับซ้อนเกินไป
  • ใช้ Multi-factor Authentication (MFA) ร่วมด้วย