如何将多个正则表达式与不同的验证消息一起使用 [英] How can I use multiple regex expressions with different validation messages

查看:88
本文介绍了如何将多个正则表达式与不同的验证消息一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求

我想通过使用多个正则表达式来检查密码策略.对于每个违反政策的行为,我想显示一条特定的验证消息.

I want to check password policies by using multiple regex expressions. For each policy violation I want to display a specific validation message.

示例:

  • 您需要至少使用2个数字
  • 您需要至少使用一个大写字母和一个小写字母
  • 您至少需要使用8个字母
  • ...

尝试

我尝试使用多个正则表达式(Fluent Validation <代码>匹配(字符串表达式)),但是ASP.NET MVC不允许具有多个正则表达式.

I tried to use multiple regex expressions (Fluent Validation Match(string expression)), but ASP.NET MVC does not allow to have multiple regex expressions.

多次看到以下验证类型:regex

The following validation type was seen more than once: regex

问题

如何在Fluent验证中使用多个正则表达式验证器?

How can I use multiple regex validators in Fluent Validation?

推荐答案

您可以使用在抽象验证器中定义的自定义方法:

You can use custom method defined in Abstract validator:

public class UserValidator : AbstractValidator<User> {
   public UserValidator () {
       Custom(user => { 
           Regex r1 = define regex that validates that there are at least 2 numbers
           Regex r2 = define regex for upper and lower case letters
           string message = string.Empty;
           if(!r1.IsMatch(user.password))
           {
               message += "You need to use at least 2 numbers.";
           }
           if(!r2.IsMatch(user.password))
           {
               message += "You need to use at least one upper and one lower case letter.";
           }

           return message != string.Empty;
              ? new ValidationFailure("Password", message )
              : null; 
       });
   }
}

这篇关于如何将多个正则表达式与不同的验证消息一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆