Required attribute Not working with File input in Angular Js

前端 未结 2 491
庸人自扰
庸人自扰 2020-11-30 05:03

I have a file upload control in my form.I am using Angular JS . When I put the required attribute to validate that the file is selected it is not working.

&l         


        
相关标签:
2条回答
  • 2020-11-30 05:34

    Extending @joakimbl code I will suggest the direct like this

    .directive('validFile',function(){
        return {
            require:'ngModel',
            link:function(scope,el,attrs,ctrl){
                ctrl.$setValidity('validFile', el.val() != '');
                //change event is fired when file is selected
                el.bind('change',function(){
                    ctrl.$setValidity('validFile', el.val() != '');
                    scope.$apply(function(){
                        ctrl.$setViewValue(el.val());
                        ctrl.$render();
                    });
                });
            }
        }
    })
    

    and in html you can use like this

    <input type="file" name="myFile" ng-model="myFile" valid-file />
    <label ng-show="myForm.myFile.$error.validFile">File is required</label>
    
    0 讨论(0)
  • 2020-11-30 05:42

    It's the ngModelController that does the validation in Angular based on attributes like require. However, currently there is no support for input type="file" with the ng-model service. To get it working you could create a directive like this:

    app.directive('validFile',function(){
      return {
        require:'ngModel',
        link:function(scope,el,attrs,ngModel){
          //change event is fired when file is selected
          el.bind('change',function(){
            scope.$apply(function(){
              ngModel.$setViewValue(el.val());
              ngModel.$render();
            });
          });
        }
      }
    });
    

    Example markup:

      <div ng-form="myForm">
        <input id="userUpload" ng-model="filename" valid-file name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
        <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
        <p>
          Input is valid: {{myForm.userUpload.$valid}}
          <br>Selected file: {{filename}}
        </p>
      </div>
    

    Check out my working plnkr example.

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