【问题标题】:Validation failed due to manually inserted value由于手动插入值,验证失败
【发布时间】:2018-05-01 11:11:17
【问题描述】:

正在使用此手动插入文件名的值

<input type="file" ngf-select ng-model="file" name="file" id="file" onchange="document.getElementById('fileName').value = this.value.split('\\').pop().split('/').pop()" required>

正在使用用户选择的文件将文件名注入到文件名字段中。验证失败,因为它将该字段视为仍然为空,直到我至少再插入一个字符。我能做些什么来解决这个问题?

这是验证部分

<p ng-show="fileNameForm.fileNameInput.$error.required && fileNameForm.fileNameInput.$touched" class="help-block">File name is required.</p>

以及实际的文本字段

<input name="fileNameInput" class="form-control" type="text" id="fileName" ng-model="document.fileName" ng-maxlength="255" required>

【问题讨论】:

    标签: html angularjs validation


    【解决方案1】:

    如果模型以编程方式而不是通过更改输入值进行更改,则不会评估更改

    您可以使用 $scope.$watch 来检测 ng-model 上的更改

    $scope.$watch('document.fileName', function(newValue, oldValue) {
      //if(newValue not valid)
      //    display validation error
    });
    

    【讨论】:

    • 我不明白如何处理这段代码。我把它放在控制器里,但它似乎不起作用。
    • 因为您以编程方式设置文件名 onchange 将无法检测到 document.fileName 的更改。出于这个原因,您可以使用 $scope.$watch 来检测更改。在 $scope.$watch 中,您可以检查 newValue 以查看它是否包含有效的文件名,并相应地设置验证消息的条件。
    • 即使模型上有手表,它也只能识别键盘的手动输入,而不能识别以编程方式插入的文件名。 Watch 将其视为没有发生任何事情,就像没有插入任何内容一样。
    • 查看watch里面newValue的值,看看fileName的新值
    • $scope.$watch('document.fileName', function(newValue, oldValue) { console.log(oldValue); console.log(newValue); });
    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    相关资源
    最近更新 更多