究竟什么被归类为C#中的“符号”?

时间:2016-09-15 16:15:59

标签: c# char passwords console-application symbols

所以我正在尝试编写一个要求您创建密码的程序。我有一个代码块,用于检查用户输入的字符串是否包含符号。当布尔值'validPassword'等于true时,我将代码设置为退出循环。

    string pleaseenterapassword = "Create a password:";
    bool validPassword = false;
    Console.WriteLine(pleaseenterapassword); // Writes to the screen "Create a password:"
    string password = Console.ReadLine(); //Sets the text entered in the Console into the string 'password'
    bool containsAtLeastOneSymbol = password.Any(char.IsSymbol);
    if (containsAtLeastOneSymbol == false) // Checks if your password contains at least one symbol
        {
            Console.WriteLine("Your password must contain at least one symbol.");
            validPassword = false;
        }

如果我输入类似“Thisismypassword905 +”的内容,此代码会成功,但如果我输入类似“Thisismypassword95 *”的内容则无效。我会很感激任何帮助。提前谢谢!

2 个答案:

答案 0 :(得分:1)

来自msdn

  

有效符号是以下类别的成员   UnicodeCategory:MathSymbol,CurrencySymbol,ModifierSymbol和   OtherSymbol。 Unicode标准中的符号是一个松散定义的集合   包含以下内容的字符:

  • 货币符号。
  • 字母符号,包括一组 数学字母数字符号以及符号,如℅,№, 和™。
  • 数字表格,例如下标和上标。
  • 数学运算符和箭头
  • 几何符号。
  • 技术符号。
  • 盲文模式。

  • 装饰符号

更新: 对于juharr,谁问为什么“*”不属于MathSymbol类别。星号不属于MathSymbols类别,您可以通过此片段进行检查。或者看看fiddle

      int ctr = 0;
      UnicodeCategory category = UnicodeCategory.MathSymbol;

      for (ushort codePoint = 0; codePoint < ushort.MaxValue; codePoint++) {
         Char ch = Convert.ToChar(codePoint);

         if (CharUnicodeInfo.GetUnicodeCategory(ch) == category) {
            if (ctr % 5 == 0)
               Console.WriteLine();
            Console.Write("{0} (U+{1:X4})     ", ch, codePoint);
            ctr++;
         } 
      }
      Console.WriteLine();
      Console.WriteLine("\n{0} characters are in the {1:G} category", 
                        ctr, category);   

答案 1 :(得分:0)

回到你的问题。我这样做:

您可以使用Asp.Net Identity Framework中的PasswordValidator但如果您不想引入此类依赖项,则很容易使用几个类来提取行为:

验证器

public class BasicPasswordPolicyValidator
    {
        /// <summary>
        ///     Minimum required length
        /// </summary>
        public int RequiredLength { get; set; }

        /// <summary>
        ///     Require a non letter or digit character
        /// </summary>
        public bool RequireNonLetterOrDigit { get; set; }

        /// <summary>
        ///     Require a lower case letter ('a' - 'z')
        /// </summary>
        public bool RequireLowercase { get; set; }

        /// <summary>
        ///     Require an upper case letter ('A' - 'Z')
        /// </summary>
        public bool RequireUppercase { get; set; }

        /// <summary>
        ///     Require a digit ('0' - '9')
        /// </summary>
        public bool RequireDigit { get; set; }

        public virtual ValidationResult Validate(string item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            var errors = new List<string>();
            if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength)
                errors.Add("Password is too short");
            if (RequireNonLetterOrDigit && item.All(IsLetterOrDigit))
                errors.Add("Password requires non letter or digit");
            if (RequireDigit && item.All(c => !IsDigit(c)))
                errors.Add("Password requires digit");
            if (RequireLowercase && item.All(c => !IsLower(c)))
                errors.Add("Password requires lowercase");
            if (RequireUppercase && item.All(c => !IsUpper(c)))
                errors.Add("Password requires uppercase");

            if (errors.Count == 0)
                return new ValidationResult
                {
                    Success = true,
                };

            return new ValidationResult
            {
                Success = false,
                Errors = errors
            };
        }

        /// <summary>
        ///     Returns true if the character is a digit between '0' and '9'
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public virtual bool IsDigit(char c)
        {
            return c >= '0' && c <= '9';
        }

        /// <summary>
        ///     Returns true if the character is between 'a' and 'z'
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public virtual bool IsLower(char c)
        {
            return c >= 'a' && c <= 'z';
        }

        /// <summary>
        ///     Returns true if the character is between 'A' and 'Z'
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public virtual bool IsUpper(char c)
        {
            return c >= 'A' && c <= 'Z';
        }

        /// <summary>
        ///     Returns true if the character is upper, lower, or a digit
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public virtual bool IsLetterOrDigit(char c)
        {
            return IsUpper(c) || IsLower(c) || IsDigit(c);
        }
    }

验证结果

public class ValidationResult
    {
        public bool Success { get; set; }
        public List<string> Errors { get; set; }
    }

您的主要功能:

var pleaseenterapassword = "Create a password:";
            bool validPassword;

            //Initialize the password validator according to your needs
            var validator = new BasicPasswordPolicyValidator
            {
                RequiredLength = 8,
                RequireNonLetterOrDigit = true,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false
            };

            do
            {
                Console.WriteLine(pleaseenterapassword); // Writes to the screen "Create a password:"
                var password = Console.ReadLine(); //Sets the text entered in the Console into the string 'password'

                var validationResult = validator.Validate(password);
                validPassword = validationResult.Success;
                Console.WriteLine("Your password does not comply with the policy...");
                foreach (var error in validationResult.Errors)
                    Console.WriteLine("\tError: {0}", error);

            } while (!validPassword);

希望这有帮助!