6

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?

3 Answers 3

9

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

Comments

3

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.

2 Comments

Yes but usability wins (joke)
This is false. You can get the filename for a <input type="file" /> and see if it is blank or has a valid extension. You just can't set it or get the local path to the file.
0
<input type="file" name="path" required>

this works for me in html5

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.