1

我正在尝试在我正在编写的 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;
    }
}

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

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

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

4

1 回答 1

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)
于 2012-05-01T13:09:06.447 回答