Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client validation of INPUT of type FILE without postback using jQuery

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?

like image 237
Fixer Avatar asked Jan 02 '11 05:01

Fixer


2 Answers

@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." />
like image 96
Brian Avatar answered Nov 04 '22 15:11

Brian


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.

like image 29
x0n Avatar answered Nov 04 '22 13:11

x0n