代码之家  ›  专栏  ›  技术社区  ›  user9065477

输入文件为空时验证输入文件

  •  0
  • user9065477  · 技术社区  · 8 年前

    我有这个输入文件:

    剃须刀:

    @Html.TextBox("archivo", "", new { type = "file",id = "archivo" }
    

    Html:

    <input id="archivo" name="archivo" type="file" value="">
    

    当我按下按钮时,如果输入值为空,我想捕获消息:

    <button type="button" id="btnCargarCsv" class="btn btn-primary">Cargar</button>

    因此,在clic函数中,我尝试将消息发送为:

     $("#btnCargarCsv").on("click", function () {
            if ($('#archivo').val() == null) {
                $('#resultado').html('you need to select file');
            }
            var data = new FormData();
            data.append("archivo", $("#archivo")[0].files[0]);
    
            $.ajax({
                "type": "POST",
                "url": "/Configuracion/CargaCSV",
                   ...
    

    但当输入为空时,它不会抛出消息,因为它不会命中:

    $('#resultado').html('you need to select file');

    like输入不为空。我做错了什么?

    5 回复  |  直到 8 年前
        1
  •  4
  •   Vishnu Bhadoriya    8 年前

    使用空字符串而不是null进行验证。。

    此外,还要研究: Link 对于null和empty之间的差异

    并且可能: Link

    $("#btnCargarCsv").on("click", function () {
    
        if ($('#archivo').val() == '') {
            $('#resultado').html('you need to select file');
            return;
        }
    
        var data = new FormData();
        data.append("archivo", $("#archivo")[0].files[0]);
    
        $.ajax({
            "type": "POST",
            "url": "/Configuracion/CargaCSV",
                ...
    
        2
  •  1
  •   4b0 Agit    8 年前

    检查长度。

    if ($('#archivo').get(0).files.length === 0) {
           $('#resultado').html('you need to select file');
    }
    
        3
  •  0
  •   Kishor Velayutham    8 年前

    试试看。。!

     if ($('#archivo').get(0).files.length === 0) {
            //console.log("No files selected.");
            //alert("Please select file..");
             $('#resultado').html('you need to select file');
    
        }
    

    希望这有帮助。。!

        4
  •  0
  •   Albin Philip    8 年前

    我不知道你的代码为什么不起作用。但是,只需添加一个 必修的 标记到html。

    <input... [whatever be your type and value].. required/>
    

    验证将由这段代码完成。

    可能它不为null,,请使用“”尝试并检查。。。

    if($('#archivo').val()=="")
    {
          //print your message
    }
    else
          //your logic goes here
    
        5
  •  0
  •   artista_14    8 年前

    您可以只检查变量是否具有真值。在你的情况下

    if(!$('#archivo').val()) {
      $('#resultado').html('you need to select file');
        return;
    }
    

    如果值为 false,0,空字符串,NaN,未定义,null