Search code examples
javascriptangularjsformsvalidationng-file-upload

Angular JS ng file upload


i'm using Angular's JS well known ng file upload directive (https://github.com/danialfarid/ng-file-upload) in a project i'm working on, but i'm having an issues regarding validations. I added the ngf-pattern directive, in order to prevent users from uploading certain file formats. This works well, and each invalid file is available in the $invalidFiles array. Is there anyway to clear this array?

I am using $invalidFiles array in order to detect when invalid file was used, and alert the user. The file is not displayed in the UI, and not added to my model, but still I cannot submit the form because the form is invalid. only after I add a valid file I can submit the form. Is there a way to detect invalid files but still be able to submit the form ?

Hope I was clear.. Thanks!


Solution

  • Probably the thing you really need is ngf-change rather then ngf-select. Based on the documentation, the handler function you assign to ngf-change directive would be called whenever you select, drop, or cleared.

    If the only thing you want to achieve is to allow form submission regardless it's valid or invalid, another approach would be leveraged on ng-model-options. There is an option called allowInvalid, by default it's false, set it to true would do the trick.

    So in your example:

    <button name="bla" multiple accept="image/*"              
            ngf-keep="true" 
            ng-model="myFiles" 
            ngf-pattern="'image/*'" 
            ngf-max-size="1MB"
            ngf-change="handleFiles($files, $invalidFiles)"
            ngf-model-options="{allowInvalid: true}">
      Select Files
    </button>
    

    Notice the last two directives we have changed here.

    For full reference, you may check the official document at the section of Full reference - File select and drop