RegularExpressionAttribute不工作,我不知道为什么

时间:2011-04-19 22:15:51

标签: regex asp.net-mvc-2 attributes

我有一个MVC2的简单视图模型类,它具有MagicItem属性:

public class VoodooViewModel {

  [Required(AllowEmptyStrings = false, 
            ErrorMessage = "The Magic Item is required")]
  [RegularExpression(@"^[^-]*$", 
                     ErrorMessage = "Hyphens are not allowed in Magic Items.")]
  public string MajorModel { get; set; }
}

我只是试图在这个属性中禁止连字符,但对于我的生活,我无法让它工作。谁能看到我做错了什么(RequiredAttribute工作正常)?

在我看来,我所说的正则表达式“从字符串的开头到结尾,匹配任何不是连字符的东西”。我在Regex测试器here中对此进行了测试,但它确实有效 - 但不在我的代码中。无论我放入多少个连字符,我都无法显示错误。

1 个答案:

答案 0 :(得分:1)

像工具一样,我忘记检查控制器的操作方法,看看ModelState是否有效:

public ActionResult UberController(VoodooViewModel vvm)
{
  if (!ModelState.IsValid) return View(vvm);  //turns out this line is important

  (...yaddayaddayadda...)
}

感谢Darin让我指向了正确的方向。

相关问题