Reputation: 3429
ASP.NET MVC Core if that makes any difference
Is there a simple way to disable some field validators in a model or view under certain cases?
Most information on the web looks to be from the ASP.NET Forms era. I could not find too many things to try out but, this looks to not do the trick.
<label asp-for="Files.PromoImage" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Files.PromoImage" class="form-control" />
@if (Model.Content.NewArticle)
{
<span asp-validation-for="Files.PromoImage" class="text-danger"></span>
}
</div>
<div class="col-md-8">
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
</div>
Upvotes: 1
Views: 861
Reputation: 4336
<input asp-for="Files.PromoImage"/>
will generate validation span and data-required
attribute if the PromoImage
property is marked with the [Required]
attribute. You can check the generated html in the browser.
The easiest way to achieve what you want is to remove the [Required]
attribute in the model and have something like this in the view:
@if (Model.Content.NewArticle)
{
<input class="form-control" data-val="true"
data-val-required="The PromoImage field is required." name="Files.PromoImage"
placeholder="Promo Image" type="text" value="">
}
else
{
<input asp-for="Files.PromoImage" class="form-control"/>
}
Then again on the server, in your post action method, you have to do a manual validation for the PromoImage
property.
Not so trivial but more elegant approach is to extend the MVC and jQuery validation with your own validation attribute and jQuery validator, e.g. [RequiredIf]
. The API is slightly different in ASP.NET Core 1.0, but here is an example: Custom validation
Upvotes: 1