I want to use conditional validation in my application, but i cant't seem to figure it out. The data annotations validation is working fine, and if i leave the field empty with will return to the form with indication of such, but nothing happens for the conditional one. I would very much like if I could keep extra code out of the controller, views, and EF generated files (that's why I'm using the sealed class). ("ConditionIsMet" will obviously be something that returns a boolean and is there just as an example). What am I missing?
This is the code I have so far:
View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>TestApplications</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FullName)
@Html.ValidationMessageFor(model => model.FullName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>'
Controller:
[HttpPost]
public ActionResult TestApplication(TestApplications application)
{
if (ModelState.IsValid)
{
DB_connection.TestApplications.Add(application);
DB_connection.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
My custom class file:
[MetadataType(typeof(TestApplicationsMetadata))]
public partial class TestApplications
{
internal sealed class TestApplicationsMetadata : IValidatableObject
{
[Required(ErrorMessage = "Name is required.")]
public string FullName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!conditionIsMet)
{
yield return new ValidationResult
("Condition was not met", new[] { "FullName" });
}
}
}
}