Jquery 如果文件未上传,验证会出错

Jquery Validate gives error if file not uploaded

我正在使用 jQuery 验证我的表单。所有验证规则都运行良好,但我在文件验证方面遇到了一些问题。

我有 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());
      }
    });
  })
});

问题是因为文件大小检查始终运行,无论该字段是否为必填项。因此,如果该字段中未提供文件,验证将拒绝提交。

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

$.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;
});