简体   繁体   中英

How to validate files with required in angularjs?

Hi I am developing angularjs application. I have file upload module. Below is my html code.

<input type="file"  file-modelsr="myFileID" name="fileupld" valid-files required />

On submitting form I am trying to get something like this below.

console.log(form2.fileupld.$valid);

This always gives me undefined. How can i check file has been uploaded or not on submitting the form?

I have used below directive.

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

I used below directive to upload files.

myapp.directive('fileModelsr', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModelsr);
            var modelSetter = model.assign;
            element.bind('change', function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

How can I apply required file validation in AngularJS?

You can change your fileModel directive to the following and get rid of validFiles directive. Check if your fileModelsr has any value or not and validate based on this.

JS :

.directive('fileModel', ['$parse', '$rootScope', function($parse, $rootScope) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModelsr);
            var modelSetter = model.assign;
            element.bind('change', function() {
                scope.$apply(function() {
                    modelSetter(scope, element[0].files[0]);
                    if (element[0].files[0]) {
                        $rootScope.fileUploaded = true;
                    }
                });
            });
        }
    };
}])

HTML :

<input type="file" file-modelsr="myFileID" name="fileupld" required />
<button type="submit" name="submit" class="btn btn-primary" ng-disabled="!fileUploaded" ng-click="uploadFile()">Submit</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM