javascript 验证不适用于具有“必需”属性的文件输入 - AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22795404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:47:01  来源:igfitidea点击:

Validation doesnt work for File Input with 'Required' attribute- AngularJS

javascriptangularjsvalidationangularjs-scopeangularjs-ng-form

提问by Neel

I have been playing around this and couldnt get it to work. I was creating an angular form and I was able to get the validation to work when requiredattribute is added to the text field. However, if a input type fileis added with requiredattribution, I noticed that the $error.requiredtext is shown but it doesnt validation even if a file is chosen. Its still showing as invalid even after adding a file. I have created a sample in jsfiddle so you can check this out: http://jsfiddle.net/Alien_time/kxSaz/6/

我一直在玩这个,但无法让它工作。我正在创建一个有角度的表单,当required属性添加到文本字段时,我能够使验证工作。但是,如果输入类型file添加了required属性,我注意到会显示$error.required文本,但即使选择了文件也不会验证。即使添加了文件,它仍然显示为无效。我在 jsfiddle 中创建了一个示例,因此您可以查看:http: //jsfiddle.net/Alien_time/kxSaz/6/

Doesnt validation work for file inputs? How can I add a required option and validate it when using file select?

文件输入的验证不起作用吗?如何在使用文件选择时添加所需选项并验证它?

回答by Jake Johnson

ngModelControllerdoesn't currently support input type=file.

ngModelController当前不支持输入类型=文件。

you can solve your issue with a custom directive.

您可以使用自定义指令解决您的问题。

app.directive('validFile',function(){
  return {
    require:'ngModel',
    link:function(scope,el,attrs,ngModel){
      el.bind('change',function(){
        scope.$apply(function(){
          ngModel.$setViewValue(el.val());
          ngModel.$render();
        });
      });
    }
  }
});

see usage here

在此处查看用法