2
我瞭解如何創建自定義驗證屬性。事實上,當我使用Seed方法預先填充數據庫時,正在執行Validate方法,如果它失敗,則會引發異常。 但是,驗證不適用於實體的創建表單。CustomValidation屬性不適用於ASP.NET MVC 3和EF
我必須改變HTML(剃刀形式)的東西嗎?
它只是讓我添加驗證失敗的項目。
代碼在這裏:
namespace Data.Model
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class YearsValidationAttribute : ValidationAttribute
{
// Internal field to hold the min value.
readonly int _years;
public int Years
{
get { return _years; }
}
public YearsValidationAttribute(int years)
{
_years = years;
}
public override bool IsValid(object value)
{
var years = (int)value;
bool result = true;
if (this.Years != null)
{
result = Years >= years;
}
return result;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name, Years);
}
}
}
public class Position
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int PositionID { get; set; }
[Required(ErrorMessage = "Position name is required.")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
[Display(Name = "Position name")]
public string name { get; set; }
[Required(ErrorMessage = "Number of years is required")]
[Display(Name = "Number of years")]
[YearsValidationAttribute(5, ErrorMessage = "{0} value must be greater than {1} years.")]
public int yearsExperienceRequired { get; set; }
public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Position</legend>
@Html.HiddenFor(model => model.PositionID)
<div class="editor-label">
@Html.LabelFor(model => model.name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.yearsExperienceRequired)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.yearsExperienceRequired)
@Html.ValidationMessageFor(model => model.yearsExperienceRequired)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
實際上,您在此處粘貼的代碼已經擁有了,問題是我正在進行驗證,我改變了它,並且它可以正常工作。它甚至在文本框旁邊顯示驗證消息。但我也會嘗試客戶端驗證。 –
它爲你工作的好。你是什麼意思「向後驗證」? –
它是結果=年> =年,正確的方式是結果=年> =年。 –