Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

<input id="userUpload" name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

<button type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>

Can you please suggest why the required is not working ?

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

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.

share|improve this answer
    
will this work on IE 8 and above ? –  Moiz Apr 25 '13 at 8:08
    
Yes, if you follow the angular ie guide docs.angularjs.org/guide/ie –  joakimbl Apr 25 '13 at 8:11
    
I have already included SHIV for IE. I am going to put this code.will this work ? –  Moiz Apr 25 '13 at 8:13
    
I don't even know what your code does - my sniplet should be IE8 compatible. Include it, test it and if it doesn't work in IE8 create a new question –  joakimbl Apr 25 '13 at 8:17
1  
Your example throws an exception in jQuery. –  Jon Rimmer Jul 17 '13 at 13:58
show 3 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.