简体   繁体   English

如何在angularjs中使用必填项验证文件?

[英]How to validate files with required in angularjs?

Hi I am developing angularjs application. 嗨,我正在开发angularjs应用程序。 I have file upload module. 我有文件上传模块。 Below is my html code. 下面是我的html代码。

<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? 如何在AngularJS中应用所需的文件验证?

You can change your fileModel directive to the following and get rid of validFiles directive. 您可以将fileModel指令更改为以下内容,并摆脱validFiles指令。 Check if your fileModelsr has any value or not and validate based on this. 检查您的fileModelsr是否具有任何值,然后根据此值进行验证。

JS : 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 : 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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