Client validation of INPUT of type FILE without po

2019-06-21 05:51发布

问题:

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?

回答1:

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:

@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." />


回答3:

<input type="file" name="path" required>

this works for me in html5