将变量与模型属性进行比较

时间:2015-05-07 20:18:50

标签: c# regex attributes

我有一个班级:

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;
}

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

2 个答案:

答案 0 :(得分:1)

使用Regex.IsMatch方法:

SELECT `table1`.* 
FROM `table1` 
LEFT JOIN `table1` t
ON `table1`.reference_id  = t.reference_id 
 AND `table1`.id<t.id
WHERE `table1`.reference_id IN(2,3)
  AND t.id IS NULL
GROUP BY `table1`.reference_id 

修改

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

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;
}

答案 1 :(得分:0)

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

你可以把它组合成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}$)检查长度。