【问题标题】:What Is the Regex Patten for only special characters not digits and alphabets (Using fluent validation with .Matches())?)什么是仅用于特殊字符而非数字和字母的正则表达式模式(使用 .Matches() 的流畅验证)?)
【发布时间】:2016-05-19 12:58:47
【问题描述】:

例如:

Rule(x=x.Password)
    .Matches(@"(**?:[^​˜!@#$]*[˜​!@#$]**){" + count+ "}")
    .WithMessage("Password should contain at least {0} special character(s)", count);

此处不匹配所有特殊字符,如点、加号等。

【问题讨论】:

    标签: .net c#-5.0 fluentvalidation


    【解决方案1】:

    像下面这样声明正则表达式变量。

    readonly Regex regEx = new Regex("^[a-zA-Z0-9]*$");
    

    参考下面的代码使用。

    RuleFor(x=x.Password).Cascade(CascadeMode.StopOnFirstFailure)
                 .Matches(regEx)
                 .WithMessage("Password should contain at least {0} special character(s)", "Password"));
    

    【讨论】:

    • 您能否提供不接受计数为 {5}、{6} 等的 [a-zA-Z0-9] 的正则表达式
    【解决方案2】:

    我不知道如何使用单个正则表达式来执行此操作。但您可以使用custom validator 进行验证。

    class CustomerValidator : AbstractValidator<Customer>
    {
    
        public CustomerValidator()
        {
            RuleFor(customer => customer.Name).SetValidator(new PasswordValidator());
        }
    }
    
    class PasswordValidator : PropertyValidator
    {
        private const int Count = 3;
        private readonly Regex regex;
        const string expression = @"[^A-Za-z0-9]";
    
        public PasswordValidator()
            : base(() => "Property {PropertyName} is not in the correct format.")
        {
            regex = new Regex(expression, RegexOptions.IgnoreCase);
        }
        protected override bool IsValid(PropertyValidatorContext context)
        {
            if (context.PropertyValue == null) return false;
            var collection = regex.Matches((string)context.PropertyValue);
            return collection.Count >= Count;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多