IValidatableObject
ASP.NET MVC's conditional validation feature lets you define validation rules that depend on other model properties. This is invaluable when certain fields need validation only under specific circumstances.
Let's illustrate with a Person
model containing Name
, IsSenior
, and a nested Senior
class with a Description
property. We'll require Senior.Description
only if IsSenior
is true.
Here's the model using data annotations (a simpler, but less flexible approach):
<code class="language-csharp">public class Person { [Required(ErrorMessage = "*")] public string Name { get; set; } public bool IsSenior { get; set; } public Senior Senior { get; set; } } public class Senior { [Required(ErrorMessage = "*")] // This validation is not conditionally applied yet. public string Description { get; set; } }</code>
And a corresponding view snippet (illustrative):
<code class="language-html">@Html.LabelFor(m => m.Name) @Html.EditorFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) @Html.LabelFor(m => m.IsSenior) @Html.EditorFor(m => m.IsSenior) @Html.ValidationMessageFor(m => m.IsSenior) @Html.LabelFor(m => m.Senior.Description) @Html.EditorFor(m => m.Senior.Description) @Html.ValidationMessageFor(m => m.Senior.Description) </code>
IValidatableObject
For more robust conditional validation, ASP.NET MVC offers the IValidatableObject
interface. Implementing its Validate
method allows you to define validation logic based on the model's overall state.
Here's the improved Person
model using IValidatableObject
:
<code class="language-csharp">public class Person : IValidatableObject { public string Name { get; set; } public bool IsSenior { get; set; } public Senior Senior { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (IsSenior && string.IsNullOrEmpty(Senior?.Description)) yield return new ValidationResult("Description is required for senior citizens."); } }</code>
This approach offers greater flexibility and control over validation rules. For comprehensive details, consult the relevant Microsoft documentation (search for "IValidatableObject" and ASP.NET MVC). The example above utilizes the null-conditional operator (?.
) for added safety.
以上がHow to Implement Conditional Validation in ASP.NET MVC Using Data Annotations and IValidatableObject?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。