Using $setValidity inside a Controller

Churk picture Churk · Jan 16, 2013 · Viewed 121.9k times · Source

I am trying to do some validation on file change. Here is my code:

View/Template

<input type="file" name="file" id="file"  
       onchange="angular.element(this).scope().setFile(this)" 
       required />

<span class="error" ng-show="myForm.file.$error.required">Error</span>
<span class="error" ng-show="myForm.file.$error.size">Selected file is too large</span>
<span class="error" ng-show="myForm.file.$error.filetype">Unsupported File type</span>

Controller

angular.module("myapp").controller("myctrl", function($scope) {
  $scope.setFile = function(element) {
    $scope.$apply(function($scope) {
      var fileObject = element.files[0];
      $scope.file.fileType = 
         fileObject.type.toUpperCase().substring(fileObject.type.indexOf("/") + 1);

      // Validation
      if (!$scope.isValidFileType($scope.file.fileType)) {
        myForm.file.$setValidity("myForm.file.$error.filetype", false);
      }

      if (fileObject.size > 1000*1000*10) {
        myForm.file.$setValidity("myForm.file.$error.size", false);
      }
    });
  };

  $scope.isValidFileType = function(fileExtension) {
    var supportedExtensions = ["doc", "docx", "ppt", "pptx", "jpg", "gif", "png"]; // etc.
    return (jQuery.inArray(fileExtension, supportedExtensions) > -1);
  }
});

But right now the call to $setValidity is not working.
Any thoughts?

Answer

Ben Lesh picture Ben Lesh · Jan 16, 2013

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);