I want to check on the client side that a file has been selected before the form can be submitted.
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Upload", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="File" name="File" type="file" size="80" />
<input type="submit" name="name" value="Upload" />
}
Currently this form is doing postbacks for validation. What is going wrong?
@xOn is right about not being able to modify the file element, but you should be able to validate it.
Here is a file element that uses unobtrusive validation to ensure the field has a value and the correct extension before submitting.
<input type="file"
id="myImg"
name="logo"
data-val="true"
data-val-required="Oops, select the logo first!"
accept="jpg|jpeg"
data-val-accept="Sorry, we only accept jpegs." />
An input of type "file" is a security-sensitive control and is not scriptable through the DOM. Imagine hitting a page, and that page sets the value of the control to a well-known location of a sensitive file and automatically submitting the form. The last time this control was scriptable would be about 1995 or 1996. That was a very silly time for internet security.
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