Client validation of INPUT of type FILE without postback using jQuery

*爱你&永不变心* 提交于 2019-12-12 11:14:54

问题


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



来源:https://stackoverflow.com/questions/4577296/client-validation-of-input-of-type-file-without-postback-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!