8

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?

Update

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)

2 Answers 2

13

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I found that even though this all worked client side the ModelState.IsValid returned false because of the Regex Validator.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.