ASP.NET MVC 3 - 自定义验证器

时间:2012-05-01 13:03:09

标签: c# asp.net-mvc-3 razor

我正在尝试在我正在编写的ASP.NET MVC 3应用程序上实现电话号码的自定义验证器。我已经了解了自定义验证器的代码,如下所示

public class PhoneNumberValidator : ValidationAttribute 
{


    public PhoneNumberValidator() : base("The Phone Number is not Valid")
    {
    }
    public override bool  IsValid(object value)
    {
        if (value != null)
        {
            string phonenumber = value.ToString();

            var regex = new Regex(@"^(?:[0-9]+(?:-[0-9])?)*$");

            if (regex.IsMatch(phonenumber))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }
}

然后在我的Model类中,我有以下内容:

    [Display(Name = "PhoneNumber")]
    [Required(ErrorMessage = "Is Phone Number Required")]
    [PhoneNumberValidator]
    public string PhoneNumber { get; set; }

然而,当我运行我的应用程序并单击页面上的继续按钮时,如果输入的值是字母,则不会抛出错误,但如果我设置了断点,我可以看到该值正在读入字符串phonenumber ok。我错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:3)

你似乎正在重新发明轮子。为什么不使用现有的正则表达式验证器:

public class MyViewModel
{
    [Display(Name = "PhoneNumber")]
    [Required(ErrorMessage = "Is Phone Number Required")]
    [RegularExpression(@"^(?:[0-9]+(?:-[0-9])?)*$")]
    public string PhoneNumber { get; set; }
}

这就是说验证由模型绑定器触发,因此请确保您提交表单的控制器操作将视图模型作为参数:

[HttpPost]
public ActionResult Process(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the model is invalid => redisplay view
        return View(model);
    }

    // at this stage the model is valid => you could do some processing here 
    // and redirect
    ...
}

或使用TryUpdateModel方法(我个人更喜欢以前的方法):

[HttpPost]
public ActionResult Process(FormCollection some_Dummy_Parameter_Thats_Not_Used_At_All_But_Which_We_Need_To_Avoid_The_Method_Overloading_Error_With_The_GET_Action_Which_Has_The_Same_Name)
{
    var model = new MyViewModel();
    if (!TryUpdateModel(model))
    {
        // the model is invalid => redisplay view
        return View(model);
    }

    // at this stage the model is valid => you could do some processing here 
    // and redirect
    ...
}

另外,为了在某处显示错误消息,请确保在视图中有相应的占位符:

@Html.EditorFor(x => x.PhoneNumber)
@Html.ValidationMessageFor(x => x.PhoneNumber)

或使用验证摘要助手:

@Html.ValidationSummary(false)