I am sure I am missing something here, I found this question to validate a file, here is the sample code
public class UpdateSomethingViewModel
{
[DisplayName("evidence")]
[Required(ErrorMessage="You must provide evidence")]
[RegularExpression(@"^abc123.jpg$", ErrorMessage="Stuff and nonsense")]
public HttpPostedFileBase Evidence { get; set; }
}
but I don't see any @Html.FileFor(model => model.Evidence)
Any ideas?
I found a simple solution passing attribute type in html attribute collection.
@Html.TextBoxFor(model => model.Evidence, new { type = "file" })
@Html.ValidationMessageFor(model => model.Evidence)
I found a simple solution passing attribute type
in html attribute collection.
@Html.TextBoxFor(model => model.Evidence, new { type = "file" })
@Html.ValidationMessageFor(model => model.Evidence)
I am afraid you can't do this using data annotations. You could do this in the controller action that is supposed to handle the request:
Model:
public class UpdateSomethingViewModel
{
[DisplayName("evidence")]
[Required(ErrorMessage = "You must provide evidence")]
public HttpPostedFileBase Evidence { get; set; }
}
Action:
[HttpPost]
public ActionResult Foo(UpdateSomethingViewModel model)
{
if (model.Evidence != null && model.Evidence.ContentLength > 0)
{
// the user uploaded a file => validate the name stored
// in model.Evidence.FileName using your regex and if invalid return a
// model state error
if (!Regex.IsMatch(model.Evidence.FileName, @"^abc123.jpg$"))
{
ModelState.AddModelError("Evidence", "Stuff and nonsense");
}
}
...
}
Also note that it is better to use HttpPostedFileBase
rather than the concrete HttpPostedFileWrapper
type in your model. It will make your life easier when you are writing unit tests for this controller action.
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