CustomValidation属性はASP.NET MVC 3およびEFで動作していません
質問
カスタム検証属性を作成する方法を理解しました。実際、Seedメソッドを使用してデータベースを事前に入力すると、検証メソッドが実行されています。ただし、検証はエンティティの作成形式では機能していません。
何かをHTML(Razor Form)に変更する必要がありますか?
検証に失敗したアイテムを追加できるようになります。
ここでコード:
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>
}
解決
あなたが持っているそのコードは、あなたにクライアントバリエーターを与えません、サーバー側のみ。しかし、それは良い出発点です。サーバー上のアクション方法で必要なことは、モデルがそのように有効であるかどうかを確認することです。
public ActionResult YourAction(YourModel model)
{
if(ModelState.IsValid)
{
// Do your save
}
else
{
// Do your other stuff
}
}
クライアントサイドの検証も必要な場合は、こちらのリソースを使用できます。 http://bradwilson.typepad.com/blog/2010/10/MVC3-Onobtrusive-Validation.html
使用することもできます Remote
検証属性: http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
所属していません StackOverflow