2010-11-19 6 views
0

アプリケーションに検証を追加しようとしています。私は、情報をデータベースに書き込む前に確認する必要のあるいくつかの規則を持っています。私は基本的なデータ検証をモデルに追加しましたが、あるフィールドにある値がある場合は、この他のフィールドも必要であることを確認する必要があります。 NerdDinnerのチュートリアルasp.netはこれをカバーしていましたが、過去に検証のために使用しましたが、今ではそれを見つけることができません。ASP.NET MVC2アプリケーションのカスタム検証ルール

public class DayRequested 
{ 
    public int RequestId { set; get; } 
    [Required, DisplayName("Date of Leave")] 
    public string DateOfLeave { get; set; } 
    [Required, DisplayName("Time of Leave")] 
    public string TimeOfLeave { get; set; } 
    [Required, DisplayName("Hours Requested")] 
    [Range(0.5, 24, ErrorMessage = "Requested Hours must be within 1 day")] 
    public double HoursRequested { get; set; } 
    [Required, DisplayName("Request Type")] 
    public string RequestType { get; set; } 
    [DisplayName("Specify Relationship")] 
    public string Relationship { get; set; } 
    [DisplayName("Nature of Illness")] 
    public string NatureOfIllness { get; set; } 
    public bool AddedToTimesheet { get; set; } 

    public bool IsValid 
    { 
     get { return (GetRuleViolations().Count() == 0); } 
    } 

    public IEnumerable<RuleViolation> GetRuleViolations() 
    { 
     if (String.IsNullOrEmpty(DateOfLeave)) 
      yield return new RuleViolation("Date of Leave Required", "DateOfLeave"); 
     if (String.IsNullOrEmpty(TimeOfLeave)) 
      yield return new RuleViolation("Date of Leave Required", "TimeOfLeave"); 
     if ((HoursRequested < 0.5) || (HoursRequested > 24)) 
      yield return new RuleViolation("Hours must be in a period of one day", "HoursRequested"); 
     if (String.IsNullOrEmpty(RequestType)) 
      yield return new RuleViolation("Request Type is required", "RequestType"); 
     if ((!String.IsNullOrEmpty(NatureOfIllness)) && (NatureOfIllness.Length < 3)) 
      yield return new RuleViolation("Nature of Illness must be longer 2 characters", "NatureOfIllness"); 

     // Advanced data validation to make sure rules are followed 
     LeaveRequestRepository lrr = new LeaveRequestRepository(); 
     List<LeaveRequestType> lrt = lrr.GetAllLeaveRequestTypes(); 
     LeaveRequestType workingType = lrt.Find(b => b.Id == Convert.ToInt32(RequestType)); 

     if ((String.IsNullOrEmpty(Relationship)) && (workingType.HasRelationship)) 
      yield return new RuleViolation("Relationship is Required", "Relationship"); 
     if ((String.IsNullOrEmpty(NatureOfIllness)) && (workingType.HasNatureOfIllness)) 
      yield return new RuleViolation("Nature of Illness is Required", "NatureOfIllness"); 

     yield break; 
    } 
} 

マイコントローラ:

// 
    // POST: /LeaveRequest/Create 
    [Authorize, HttpPost] 
    public ActionResult Create(LeaveRequest leaveRequest, List<DayRequested> requestedDays) 
    { 
     if (ModelState.IsValid) 
     { 
      foreach (DayRequested requestedDay in requestedDays) 
      { 
       requestedDay.RequestId = leaveRequest.RequestId; 
       requestedDay.NatureOfIllness = (String.IsNullOrEmpty(requestedDay.NatureOfIllness) ? "" : requestedDay.NatureOfIllness); 
       requestedDay.Relationship = (String.IsNullOrEmpty(requestedDay.Relationship) ? "" : requestedDay.Relationship); 

       if (requestedDay.IsValid) 
        lrRepository.CreateNewLeaveRequestDate(requestedDay); 
       else 
        return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes())); 
      } 

      if (leaveRequest.IsValid) 
       lrRepository.CreateNewLeaveRequest(leaveRequest); 
      else 
       return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes())); 
     } 
     else 
      return View(new LeaveRequestViewModel(leaveRequest, requestedDays, lrRepository.GetLeaveRequestTypes())); 

     return RedirectToAction("Index", lrRepository.GetLeaveRequests(udh.employeeId)); 
    } 

ModelState.IsValid

IsValidでコードが実行されるがfalseに設定されていないと RuleViolationを返さないここに私のモデルです。だから私は手動で IsValidをチェックして、 falseを返します。ビューに戻ると、エラーメッセージは表示されません。私は何が欠けていますか?ここではいくつかのビューの抜粋です。

Create.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2>Create New Leave Request</h2> 
    <div><%= Html.ActionLink("Back to List", "Index") %></div> 
    <%= Html.Partial("RequestEditor", Model) %> 
    <div><%= Html.ActionLink("Back to List", "Index") %></div> 
</asp:Content> 

RequestEditor.ascx

<% using (Html.BeginForm()) {%> 
    <%= Html.ValidationSummary(true) %> 
     <table id="editorRows"> 
      <% foreach (var item in Model.DaysRequested) 
       Html.RenderPartial("RequestedDayRow", new EmployeePayroll.ViewModels.LeaveRequestRow(item, Model.LeaveRequestType)); %> 
     </table> 
     <p>Type your time to sign your request.</p> 
     <p><%= Html.LabelFor(model => model.LeaveRequest.EmployeeSignature) %>: 
      <%= Html.TextBoxFor(model => model.LeaveRequest.EmployeeSignature, new { Class="required" })%> 
      <%= Html.ValidationMessageFor(model => model.LeaveRequest.EmployeeSignature)%></p> 
     <p><input type="submit" value="Submit Request" /></p> 
<% } %> 

RequestedDayRow.ascx

<tbody class="editorRow"> 
    <tr class="row1"></tr> 
    <tr class="row2"> 
     <td colspan="2" class="relationship"> 
      <%= Html.LabelFor(model => model.DayRequested.Relationship)%>: 
      <%= Html.TextBoxFor(model => model.DayRequested.Relationship) %> 
      <%= Html.ValidationMessageFor(model => model.DayRequested.Relationship)%> 
     </td> 
     <td colspan="2" class="natureOfIllness"> 
      <%= Html.LabelFor(model => model.DayRequested.NatureOfIllness)%>: 
      <%= Html.TextBoxFor(model => model.DayRequested.NatureOfIllness) %> 
      <%= Html.ValidationMessageFor(model => model.DayRequested.NatureOfIllness)%> 
     </td> 
     <td></td> 
    </tr> 
</tbody> 

答えて

1

それは終了しています単純です - 検証属性をモデル全体(または子クラス)に適用するだけで済みます。次に、検証属性は、ただ1つのプロパティではなくモデルへの参照を取得し、複数のプロパティのチェックを実行できます。

+0

うん、私はこれを掲示した後、もう一度振り返りました。 NerdDinnerの例では、 'ModelState.AddRuleViolations()'というヘルパーメソッドを使用しました。これは違反を 'ModelState.AddModelError()'に追加しました。ありがとう! –

0

これを行う方法の例については、パスワードの検証をご覧ください。

がここPropertiesMustMatchバリデータをチェックアウト:

http://msdn.microsoft.com/en-us/magazine/ee336030.aspx

+0

それは彼が望んでいるものではありません。 –

+0

これは、検証属性を使用して2つのプロパティを比較しています。 – rboarman

関連する問題