2011-04-20 179 views
1

我創建了一個自定義驗證我的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> 
} 

但驗證不會觸發。請建議解決方案。

謝謝

回答

2

您如何知道驗證不會觸發?你是否在你的控制器中設置了一個斷點?

您在視圖中未顯示任何驗證錯誤。您需要將以下行添加到視圖中。

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

您將要從類中刪除自定義驗證。儘管如此,留在屬性。