【问题标题】:Compare Variable with Model Attributes比较变量与模型属性
【发布时间】:2015-05-08 06:01:58
【问题描述】:

我有一堂课:

public class Email
{
    [RegularExpression("^[a-zA-Z0-9_\\+-]+(\\.[a-zA-Z0-9_\\+-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,4}$", ErrorMessage = "Must enter valid email.")]
    [StringLength(256)]
    public string Address { get; set; }
 }

我有一个包含“坏”数据的数据库,其中我的新 RegEx 不再支持 Address

我的代码如下:

Email newUser = new Email();
foreach (string email in user.Emails)
{
   // Something here to check the value 'email' fits the RegEx
   newUser.Address = email;
}

有没有办法确保我要分配的值与正则表达式匹配?

【问题讨论】:

  • 是否还需要实现长度限制?最多 256 个字符?
  • 我认为任何电子邮件地址都不会接近限制,但可以说是的......该代码看起来如何?
  • 我发布了一个仅使用正则表达式的答案。

标签: c# regex attributes


【解决方案1】:

使用Regex.IsMatch方法:

Email newUser = new Email();
Regex regex = new Regex("^[a-zA-Z0-9_\\+-]+(\\.[a-zA-Z0-9_\\+-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,4}$");   
foreach (string email in user.Emails)
{
    if (regex.IsMatch(email) ) {
       newUser.Address = email;
    }
}

编辑

如果您想避免正则表达式模式的重复并验证其他属性,您可以使用此方法进行验证:

public bool CheckValidation(Type type, string property, object value) {
  PropertyInfo propertyInfo = type.GetProperty(property, BindingFlags.Public | BindingFlags.Instance);
  if (propertyInfo == null) {
     throw new ArgumentException("property");
  }
  var attributes = propertyInfo.GetCustomAttributes();
  foreach (var attribute in attributes) {
     if (attribute is ValidationAttribute) {
        var validationAttribute = (ValidationAttribute)attribute;
        try {
           validationAttribute.Validate(value, string.Empty);
        }
        catch (ValidationException) {
           return false;
        }
     }
  }
  return true;
}

然后这样使用:

foreach (string email in user.Emails)
{
    if (CheckValidation(typeof(Email), "Address", email) {
       newUser.Address = email;
    }
}

【讨论】:

    【解决方案2】:

    您必须实现 2 个条件:电子邮件正则表达式检查和长度检查。

    您可以将其组合成 1 个正则表达式(我还使用 (?i) 不区分大小写选项将其缩短了一点):

    Email newUser = new Email();
    Regex rxMail = new Regex(@"(?i)^(?=.{0,256}$)[a-z0-9_\+-]+(?:\.[a-z0-9_\+-]+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,4}$");
    foreach (string email in user.Emails)
    {
       if (rxMail.IsMatch(email))
       {
           newUser.Address = email;
       }
    }
    

    在模式的开头使用正向预测(?=.{0,256}$) 检查长度。

    【讨论】:

      猜你喜欢
      • 2012-10-25
      • 2018-03-20
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 2020-02-08
      • 2020-04-25
      • 1970-01-01
      相关资源
      最近更新 更多