如果文件未上传,jQuery验证会给出错误

问题描述 投票:0回答:1

我正在为表单使用jQuery Validate。所有验证规则都运行良好,但是文件验证存在一些问题。

我有3个文件输入,其中2个是必需的,而1个不是必需的。如果我全部上载了3个文件,则规则工作正常。但是,如果我没有在第三个输入(nic)中上载文件,那么它将给我一个文件大小错误,并且不运行任何验证。

$(document).ready(function() {
  $.validator.addMethod('filesize', function(value, element, arg) {
      if (element.files[0].size <= arg) {
        return true;
      } else {
        return false;
      }
    }

    $("#Cnd_reg_form").validate({
      rules: {
        passport: {
          required: true,
          extension: "docx|jpeg|png|doc|pdf",
          filesize: 4000000
        },
        license: {
          required: true,
          extension: "docx|jpeg|png|doc|pdf",
          filesize: 2000000
        },
        nic: {
          required: false,
          extension: "docx|jpeg|png|doc|pdf",
          filesize: 2000000
        }
      },
      messages: {
        passport: {
          required: "Please upload your passport",
          extension: "Please upload file with extension doc,pdf,jpeg,png",
          filesize: "Please select file under 4MB"
        },
        license: {
          required: "Please upload your license",
          extension: "Please upload file with extension doc,pdf,jpeg,png",
          filesize: "Please select file under 2MB"
        },
        nic: {
          extension: "Please upload file with extension doc,pdf,jpeg,png",
          filesize: "Please select file under 2MB"
        }
      },
      errorPlacement: function(error, element) {
        error.appendTo(element.parent());
      }
    });
  })
});
jquery jquery-validate
1个回答
0
投票

问题在于,无论是否需要该字段,文件大小检查始终运行。因此,如果该字段中未提供文件,则验证将拒绝提交。

要解决此问题,只需在检查大小之前检查文件是否为可选:

$.validator.addMethod('filesize', function(value, element, arg) {
  if (this.optional(element))
    return;

  if (element.files[0].size <= arg) {
    return true;
  } else {
    return false;
  }
});

可以进一步简化为:

$.validator.addMethod('filesize', function(value, element, arg) {
  return this.optional(element) || element.files[0].size <= arg;
});
© www.soinside.com 2019 - 2024. All rights reserved.