2014-04-09 263 views
0

我正在使用Asp.net MVC4。我有一些實體和一些規則,我需要從控制器驗證每個實體,並顯示相應的錯誤消息。我試圖設計一個通用的驗證類,它可以用於我正在使用的所有實體。如果我調用 驗證,它應該返回驗證成功或驗證錯誤列表。我將通過實體及其類型MVC4中的自定義模型驗證

一些樣品實體和規則

Employee - Employee should have either middle name or last name 
      - First name, Middle name, last name should not be same 
      - Should have address id and it should present in address table 
      ...... 
      ...... 

    Address - In address line if there is an opening bracket it should have a matching closing bracket 
      - If user give map url and it doesnt contains "http://" should show error message 
      ....... 
      ....... 

我與錯誤類型ID的資源文件中有所有的錯誤消息

請上諮詢我接受我應該遵循?或者分享我的一些網絡教程鏈接,這將幫助我設計這個

+1

我會建議你還是在這裏有一個觀點: http://fluentvalidation.codeplex.com/ HTTP ://stackoverflow.com/a/16100455/3383479 –

回答

1

您是否看過遠程驗證?這可能是您嘗試實現的好例子,因爲您有一些複雜的規則。

一些示例代碼:

public class ValidationController : Controller 
{ 

    public JsonResult IsAddressValid(string Address) 
    { 

    //if Address is valid 
    return Json(true, JsonRequestBehavior.AllowGet); 

    //else 

    return Json("Address Not valid", JsonRequestBehavior.AllowGet); 

    } 
} 

然後在你的模型

public class SignupModel 
{ 
    [Required] 
    [Remote("IsAddressValid", "Validation")] 
    public string Address{ get; set; } 
}