javascript - 输入类型=文件未使用 Jquery 验证插件传递到 php 页面

标签 javascript php jquery ajax validation

我有一个带有文件上传功能的 html 表单,我想使用 jquery 插件进行验证。现在,如果文件为空,那么它会显示一条错误消息,但如果文件的扩展名不同,那么它应该显示消息“文件类型不允许”,但它似乎没有传递到文件< strong>filecheck.php 页面将验证文件类型。

如何使用此 jquery 插件验证此文件类型?你能帮我吗?谢谢。

HTML 部分:

<div id="result"></div> <!--error or success message will be show here-->

<form action="editContactDetails.php" method="post" enctype="multipart/form-data" id="all_contact_details">
  <tr>
    <td></td>  
    <td align="left"><input name="file1" type="file" id="file" class="file"/></td>
    <td></td>
  </tr>
</form>

Jquery 部分:

$(document).ready(function() {  
    // validate signup form on keyup and submit
    $("#all_contact_details").validate({
    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            //async: false,
            data: $(form).serialize(),
            beforeSend : function (){
              $('input[type=submit]').attr('disabled', false); 
            },
            success: function(response) {
            $('#result').html(response);
            //$(form).find('div').hide();
            $(form).hide();

            }            
        });
    },

        rules: {            
            file1: {
                    required: true,                    
                    remote: {
                        url: "filecheck.php",
                        type: "post"
                     }
                },

        },
        messages: {         
            file1: {
                    required: "Upload your file",                    
                    remote: "File is not allowed"
                },          
        }
    });

});

Php 部分(filecheck.php)

<?php
$file1 =  $_FILES['file1']['name']; 
$allowedExts = array("jpg");    
$temp = stripslashes($file1);
$temp = explode(".", $temp);
$extension = end($temp);    

if(!in_array($extension, $allowedExts))
    echo 'false';
else
    echo 'true';        
?>

最佳答案

SubmitHandler在表单有效时处理实际提交:
http://jqueryvalidation.org/validate/#submithandler

所以这不会验证文件扩展名本身。

但是,您可以使用 jqueryvalidation 中内置的 extension 验证器,它将完全实现您想要实现的目标。请参阅此链接以获取引用和示例:

http://jqueryvalidation.org/extension-method/

关于javascript - 输入类型=文件未使用 Jquery 验证插件传递到 php 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24076721/

相关文章:

jquery - 像 Firebug 一样检查 html 元素

javascript - 退出和重新进入时由于某种原因复制表中的动态行?

javascript - jQuery 追加未按预期工作

javascript - "might"的正则表达式开头为,但 "must"后面为

javascript - 如何即时删除 CSS 样式

javascript - 简单的 Angular 项目不起作用

javascript - 获取 TypeError : Cannot call method 'releaseConnection' of null in mysql node. js

php - 如何配置 Firebase 安全规则以仅允许来自 CURL/PHP 源的写入?

php - 无法通过html表单更新Mysql数据库中的一列

javascript - 如何合并数据表字段?