【问题标题】:Why can't the upload field select a new file after jQuery-validate returns an error?jQuery-validate返回错误后,为什么上传字段不能选择新文件?
【发布时间】:2011-04-15 02:52:56
【问题描述】:

我正在使用 PHP 和 jQuery 编写表单。我有一个文件上传字段,我对其应用了以下 jQuery 验证规则:

image: {
 accept: "jpeg|jpg|png|gif",
 required: "#edit_ID:blank"
}

文件上传字段只能接受 jpeg/jpg、png 或 gif 图像。仅当 ID 为“edit_ID”的字段留空时才需要。

这是我的文件上传字段:

<input type="file" id="image" name="image" class="input1" />

文件上传字段选择文件没有任何问题,但是当 jQuery 因为违反规则而返回错误时,即使我从我的计算机中选择一个新文件,我在错误出现之前选择的文件仍然存在。就好像在 jQuery-validate 出错后它被禁用了。

我尝试删除该字段的规则集,测试它,没有遇到任何问题。

有人知道是什么导致了这个问题吗?

谢谢。

P.S.:我在 Firefox (v.3.6.9) 和 IE (v.8) 中遇到问题,但在 Google Chrome (v.5) 中没有。

【问题讨论】:

    标签: php validation file upload jquery-validate


    【解决方案1】:

    从技术上讲,这不会回答您最初的问题。

    但是,信任客户端编程来进行图像验证并不是一个好主意;你的程序可能会被愚弄。既然你都在使用 PHP,为什么不使用 PHP 来做一些服务器端的验证呢?

    所有上传的文件都存储在 $_FILES 数组中。您可以像这样检查文件类型:

    <?php
        foreach($_FILES as $file)
        {
            if(!empty($file['type'])) //only check if there's a valid file type
            {
                if($file['type'] != 'image/jpeg' && $file['type'] != 'image/png' && $file['type'] != 'image/gif')
                {
                    //this file is not any one of the accepted formats, so long!
                }
                else{//do your processing}
            }
            else{//error invalid file}
        }
    ?>
    

    如果您需要即时验证,您仍然可以使用 AJAX,而不是仅仅依靠客户端进行验证。

    【讨论】:

    • 我更喜欢使用客户端验证,以便在显示错误之前不会将用户带到不同的页面。如果我不知道如何解决 jQuery 问题,那么也许我会使用 PHP。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多