asp.net mvc3中的自定义验证器

时间:2011-04-20 06:44:10

标签: asp.net-mvc-3

我在我的asp.net mvc3应用程序中创建了一个自定义验证器,如下所示:

{
  if (customerToValidate.FirstName == customerToValidate.LastName)
            return new ValidationResult("First Name and Last Name can not be same.");

        return ValidationResult.Success;
    }

    public static ValidationResult ValidateFirstName(string firstName, ValidationContext context)
    {
        if (firstName == "Nadeem")
        {
            return new ValidationResult("First Name can not be Nadeem", new List<string> { "FirstName" });
        }
        return ValidationResult.Success;
    }

我装饰了我的模型:

[CustomValidation(typeof(CustomerValidator), "ValidateCustomer")]
public class Customer
{
    public int Id { get; set; }

    [CustomValidation(typeof(CustomerValidator), "ValidateFirstName")]
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

我的观点是这样的:

@model CustomvalidatorSample.Models.Customer
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
@using (@Html.BeginForm())
{
    @Html.ValidationSummary(false)

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName, "First Name")
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.LastName, "Last Name")
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
    </div>

    <div>
    <input type="submit" value="Validate" />
    </div>
}

但验证不会触发。请提出解决方案。

由于

1 个答案:

答案 0 :(得分:2)

您如何知道验证不会触发?你在控制器中设置了断点吗?

您未在视图中显示任何验证错误。您需要在视图中添加以下行。

@Html.ValidationMessageFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.LastName)

您需要从班级中删除自定义验证。把它留在属性上。

相关问题