File type validation with Javascript

后端 未结 8 867
梦谈多话
梦谈多话 2020-12-09 22:52

I have a question regarding to JavaScript validation. I am validaing the whenever my scripts runs, it validates but also the action

相关标签:
8条回答
  • 2020-12-09 22:59

    In general, you can use javascript some() method for that.

    function isImage(icon) {
      const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
      return ext.some(el => icon.endsWith(el));
    }
    
    let fname = "the file name here.ext";
    if (!isImage(fname)) {
      alert("File extension not supported!");
    }

    0 讨论(0)
  • 2020-12-09 23:01

    The return value of the submit handler affects the submission.

    onsubmit="return Checkfiles();"
    

    This is basically saying:

    form.onsubmit = function () { return Checkfiles(); };
    
    0 讨论(0)
  • 2020-12-09 23:01

    Upload bulk data through excel sheet(.csv)

    $("form").submit(function(){
     var val = $(this).val().toLowerCase();
    var regex = new RegExp("(.*?)\.(csv)$");
    if(!(regex.test(val))) {
    $(this).val('');
    alert('Only csv file can be uploaded');
    return false;
    } 
    
    });

    0 讨论(0)
  • 2020-12-09 23:04

    You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.

    0 讨论(0)
  • 2020-12-09 23:04

    You need to return CheckFiles()

    0 讨论(0)
  • 2020-12-09 23:12

    var fname = "the file name here.ext";
    var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
    if (!re.exec(fname)) {
      alert("File extension not supported!");
    }

    0 讨论(0)
提交回复
热议问题