使用 jQuery 对 FILE 类型的 INPUT 进行客户端验证,无需回发

发布于 2024-10-09 16:03:56 字数 584 浏览 0 评论 0原文

我想在提交表单之前检查客户端是否已选择文件。

<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" />    
        }

目前该表单正在进行回发以进行验证。出了什么问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暖阳 2024-10-16 16:03:56

@xOn 关于无法修改文件元素的说法是正确的,但您应该能够验证它。

这是一个文件元素,它使用不显眼的验证来确保该字段在提交之前具有值和正确的扩展名。

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

@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." />
鯉魚旗 2024-10-16 16:03:56

“文件”类型的输入是安全敏感控件,不能通过 DOM 编写脚本。想象一下点击一个页面,该页面将控件的值设置为敏感文件的已知位置并自动提交表单。上次该控件可编写脚本大约是在 1995 年或 1996 年。对于互联网安全来说,那是一个非常愚蠢的时期。

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.

梦回梦里 2024-10-16 16:03:56
<input type="file" name="path" required>

这在 html5 中对我有用

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

this works for me in html5

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文