Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate input file with jquery and dataannotation in asp.net mvc 3

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)
like image 532
k-dev Avatar asked Jun 08 '11 21:06

k-dev


2 Answers

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)
like image 79
k-dev Avatar answered Sep 28 '22 17:09

k-dev


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.

like image 22
Darin Dimitrov Avatar answered Sep 28 '22 16:09

Darin Dimitrov