0
我有一個編輯視圖,其中有一個選擇列表和一些爲空的日期字段生成的文本框。如果沒有日期,則不會進行驗證 - 這是正確的。不引人注意的驗證沒有發射可空日期字段
但是,如果我輸入了一個無效的日期,驗證不會檢測到,並繼續我的行動。我如何強制日期字段驗證?
我的模型:
public class CaseEmployer
{
public int Id { get; set; }
public int CaseId { get; set; }
public Company Company { get; set; }
[Display(Name = "Start Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode=true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
public int? UserId { get; set; }
public DateTime? TimeStamp { get; set; }
}
筆者認爲:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Employer</legend>
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.CaseId)
<div class="editor-label">
@Html.Label("Company:")
</div>
<div class="editor-field">
<select name="companySelect" id="companySelect">
@foreach (var company in ViewBag.CompanyOptions)
{
<option value="@company.Key">@company.Value</option>
}
</select>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StartDate)
@Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EndDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EndDate)
@Html.ValidationMessageFor(model => model.EndDate)
</div>
<p>
<input type="submit" value="Update" />
<input type="button" value="Cancel" onclick="javascript:window.close()" />
<input type="button" value="Delete" onclick="javascript:confirmDeleteCaseEmployer()" />
</p>
</fieldset>
**編輯**
我補充說: 「必選」 屬性的類來測試驗證會觸發,如果我提交沒有StartDate和EndDate的表單,並且驗證會觸發這些屬性。
謝謝!
哪些字段未驗證?其中一個DateTime字段沒有對其進行驗證,另外兩個都有Required驗證,那麼爲什麼它們甚至可以爲空? – 2012-01-15 13:23:46
@qes,當表單第一次呈現時,爲了顯示空白值的文本框,它們不必爲空嗎? – danludwig 2012-01-15 16:53:43
對不起,要求在那裏進行測試。 – TheGeekYouNeed 2012-01-15 22:55:45