file input MVC 3 Client-side validation for required
Asked Answered
R

2

8

Simple question... Is it possible to use client side MVC 3 validation on inputs of type file?

To explain: MVC 3 uses its model validation with IClientValidatable and unobtrusive javascript to allow you to write validation on the server side and have it render the client side using jquery validate using Microsoft's plugins. To make a property required you add the attribute below

[Required]
public HttpPostedFileBase CvFile {get; set;}

As long as client side val and unobtrusive javascript is on in the config this should all fire on the client.

However HttpPostedFileBase (i.e. <input type="file" name="Model.CvFile" />) will not run required on the client side.

Any ideas how this can be achieved keeping the relationship with the server side validation

Rump answered 12/4, 2011 at 9:30 Comment(0)
E
1

Simple answer: A HttpPostedFileBase renders "file" input type which is a security issue and, AFAIK, is not scriptable. There's no support for this "out of the box".

Edit: this seems to be a very popular topic online. http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Eats answered 12/4, 2011 at 11:54 Comment(2)
Thanks for the reply, rendering the control and building it is not a problem (code can be provided if you like). However making client side validation which is tied into is the problem. any ideas?Rump
forums.asp.net/p/1566760/4033836.aspx has a great discussion on file upload validation. From here I would create a custom validator: #5663423 or bradwilson.typepad.com/blog/2010/10/… . They might look complicated, but are well worth understanding.Eats
M
28

You need to add it manually:

<input type="file" data-val="true" data-val-required="please select a file" name="file" />
@Html.ValidationMessage("file")
Mal answered 13/7, 2012 at 13:30 Comment(0)
E
1

Simple answer: A HttpPostedFileBase renders "file" input type which is a security issue and, AFAIK, is not scriptable. There's no support for this "out of the box".

Edit: this seems to be a very popular topic online. http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Eats answered 12/4, 2011 at 11:54 Comment(2)
Thanks for the reply, rendering the control and building it is not a problem (code can be provided if you like). However making client side validation which is tied into is the problem. any ideas?Rump
forums.asp.net/p/1566760/4033836.aspx has a great discussion on file upload validation. From here I would create a custom validator: #5663423 or bradwilson.typepad.com/blog/2010/10/… . They might look complicated, but are well worth understanding.Eats

© 2022 - 2024 — McMap. All rights reserved.