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

倾然丶 夕夏残阳落幕 提交于 2019-12-01 16:04:08

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!