【问题标题】:How do I validate if a file is selected for upload before submitting a form , using jquery validator如何使用 jquery 验证器在提交表单之前验证是否选择了文件进行上传
【发布时间】:2015-06-01 13:29:19
【问题描述】:

我的 Web 应用程序中有一个页面,其中有一个上传文件的选项。在提交表单之前,我正在尝试验证是否选择了要上传的文件。我使用jQuery form validator 插件进行表单验证。

我的文件输入标签的html代码是:

<div class="form-group">
 <label for="exampleInputFile">New File</label>
 <input type="file" id="file_add" name="file">                                         
</div>

我正在尝试检查是否使用以下代码选择了任何文件:

$.formUtils.addValidator({
      name : 'file_check',
      validatorFunction : function(value, $el, config, language, $form) 
      {
      if($('#addFile').val() == "")
        return $('#file_add').val() == "" == 0;
      },
      errorMessage : 'Please choose a file',
      errorMessageKey: 'notConfirmed'
    });

但是即使没有选择要上传的文件,表单提交仍然会发生。有什么方法可以检查在提交之前是否选择了文件.....

【问题讨论】:

    标签: javascript jquery forms validation


    【解决方案1】:

    根据您提供的链接,该页面右侧窗格中有专门的文件验证部分:http://formvalidator.net/#file-validators

    我之前没有使用过这个验证器插件。话虽如此,基于this example,我相信你的代码应该是这样的:

    HTML:

    <div class="form-group">
     <label for="file_add">New File</label>
     <input type="file" id="file_add" name="file" data-validation="file_check">                                         
    </div>
    

    也就是说,我向它添加了 data-validation 属性,以及我们自定义验证的名称。

    jQuery:

    $.formUtils.addValidator({
          name : 'file_check',
          validatorFunction : function(value, $el, config, language, $form) 
          {
            if(value.trim() == "") // the "value" variable will have the value
              return false;
            else
              return true;
          },
          errorMessage : 'Please choose a file',
          errorMessageKey: 'notConfirmed'
    });
    

    我只是根据示例手写了这段代码,因此未经测试。我想这会有所帮助。

    【讨论】:

      【解决方案2】:

      你可以这样使用:

      $.formUtils.addValidator({
            name : 'file_check',
            validatorFunction : function(value, $el, config, language, $form) 
            {
              var value = $('#file_add').val();
              if(value.trim() == "") 
                return false;
              else
                return true;
            },
            errorMessage : 'Please choose a file',
            errorMessageKey: 'notConfirmed'
          });
      

      同样在你的 html 代码中,添加验证器的名称和要显示的错误消息:

      <div class="form-group">
      <label for="exampleInputFile">New File</label>
      <input type="file" id="file_add" name="file" data-validation="file_check" data-validation-error-msg="Choose An Image File To Upload" >                                         
      </div>  
      

      这应该很完美

      【讨论】:

      • 这正是我为获得预期结果所做的...谢谢
      猜你喜欢
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2017-02-22
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 2017-01-15
      相关资源
      最近更新 更多