As part of an ASP.NET Core MVC 1.0 project, I have a ViewModel with an ICollection<>
property. I need to validate that this collection contains one or more items. My custom validation attribute doesn't get executed.
In my instance it holds multiple file attachments from a multipart/form-data
form.
I have decorated the property in the ViewModel with a custom validation attribute:
[RequiredCollection]
public ICollection<IFormFile> Attachments { get; set; }
Below is the custom attribute class. It simply checks the collection is not null and has greater than zero elements:
public class RequiredCollectionAttribute : ValidationAttribute
{
protected const string DefaultErrorMessageFormatString = "You must provide at least one.";
public RequiredCollectionAttribute() : base(DefaultErrorMessageFormatString) { }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var collection = (ICollection) value;
return collection == null || collection.Count > 0
? ValidationResult.Success
: new ValidationResult(ErrorMessageString);
}
}
And finally, in the controller I am ensuring the ViewModel in the POST
request is valid, which should trigger the validation:
[HttpPost]
public async Task<IActionResult> Method(MethodViewModel viewModel)
{
if (!ModelState.IsValid)
return View(viewModel);
...
}
If I break at the ModelState.IsValid
call, the contents of ModelState.Values
for the Attachments
property is:
RequiredCollectionAttribute.IsValid()
method ever get hit?ValidationState
get set to Skipped
for the Attachments
property?--
MethodViewModel definition, as requested:
public class MethodViewModel
{
...
[Display(Name = "Attachments")]
[RequiredCollection(ErrorMessage = "You must attached at least one file.")]
public ICollection<IFormFile> Attachments { get; set; }
...
}
--
Below is the trimmed value of actionContext.ModelState
(exported in JSON), as requested. This is the state when a breakpoint is hit on entry to a global action filter, OnActionExecuting()
:
{
"Count": 19,
"ErrorCount": 0,
"HasReachedMaxErrors": false,
"IsReadOnly": false,
"IsValid": true,
"Keys":
[
"Attachments"
],
"MaxAllowedErrors": 200,
"ValidationState": Valid,
"Values":
[
{
"AttemptedValue": null,
{
},
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
}
],
{
[
"Key": "Attachments",
{
"AttemptedValue": null,
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
},
"key": "Attachments",
{
"AttemptedValue": null,
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
}
]
}
}
--
The view's razor syntax to render the Attachments
input field.
<form role="form" asp-controller="Controller" asp-action="Method" method="post" enctype="multipart/form-data">
...
<div class="form-group">
<label asp-for="Attachments" class="control-label col-xs-3 col-sm-2"></label>
<div class="col-xs-9 col-sm-10">
<input asp-for="Attachments" class="form-control" multiple required>
<span asp-validation-for="Attachments" class="text-danger"></span>
</div>
</div>
...
</form>
It looks like MVC is suppressing further validation if the IFormFile
or a collection of IFormFile
is found to be not null.
If you take a look at the FormFileModelBinder.cs
code, you can see the issue right here. It is suppressing validation if the binder is able to get a non-null result from the if/elseif/else clause above.
In a test, I made a view model with code like this:
[ThisAttriuteAlwaysReturnsAValidationError]
public IFormFile Attachment { get;set; }
When I actually upload a file to this example, the always-erroring attribute above it never gets called.
Since this is coming from MVC itself, I think your best bet for this is to implement the IValidateableObject
interface.
public class YourViewModel : IValidatableObject
{
public ICollection<IFormFile> Attachments { get;set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var numAttachments = Attachments?.Count() ?? 0;
if (numAttachments == 0)
{
yield return new ValidationResult(
"You must attached at least one file.",
new string[] { nameof(Attachments) });
}
}
}
This method will still be called as it is not associated with any individual property, and thus isn't suppressed by MVC like your attribute is.
If you've got to do this in more than one place, you could create an extension method to help.
public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection) =>
collection == null || !collection.GetEnumerator().MoveNext();
This has been filed as a bug and should be fixed in 1.0.0 RTM.
Partial Answer (just for code sharing purpses)
try this:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class RequiredCollectionAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
ErrorMessage = "You must provide at least one.";
var collection = value as ICollection;
return collection != null || collection.Count > 0;
}
}
also, try to add a filter.
GlobalConfiguration.Configuration.Filters.Add(new RequestValidationFilter());
and write the filter itself:
public class RequestValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
var errors = actionContext.ModelState
.Values
.SelectMany(m => m.Errors
.Select(e => e.ErrorMessage));
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
actionContext.Response.ReasonPhrase = string.Join("\n", errors);
}
}
}
just for us to check if a breakpoint is triggered inside the filter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With