使用 jQuery 对 FILE 类型的 INPUT 进行客户端验证,无需回发
我想在提交表单之前检查客户端是否已选择文件。
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@xOn 关于无法修改文件元素的说法是正确的,但您应该能够验证它。
这是一个文件元素,它使用不显眼的验证来确保该字段在提交之前具有值和正确的扩展名。
@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.
“文件”类型的输入是安全敏感控件,不能通过 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.
这在 html5 中对我有用
this works for me in html5