[javascript] Using $setValidity inside a Controller

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?

The answer is


$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.


A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angularjs-controller

Check if value exists in the array (AngularJS) How do I inject a controller into another controller in AngularJS Error: [ng:areq] from angular controller How do I use $rootScope in Angular to store variables? AngularJS : The correct way of binding to a service properties Using $setValidity inside a Controller AngularJS: How can I pass variables between controllers?

Examples related to angularjs-forms

Can I access a form in the controller? Using $setValidity inside a Controller