【问题标题】:validating input fields using angular and jquery?使用 Angular 和 jquery 验证输入字段?
【发布时间】:2016-08-25 21:49:30
【问题描述】:

我正在使用 angular.js 和 jQuery 来验证使用 ng-repeat 创建的表单中的用户输入。所以基本上我有一个字符串(条形码)数组,我循环显示并显示,我还显示一个输入字段。用户将使用条形码扫描仪,将其视为复制/粘贴效果,将字符串输入到输入字段中。如果条形码与旁边的字符串不匹配,则应提醒用户并清除输入字段。我有下面的代码,它使用 ng-model-options ‘Blur’ 来执行这个,它几乎可以工作。现在,每次输入不正确时,它都会提醒用户三次。我不知道为什么它会触发三遍?必须有一种更优雅的方式来使用 Angular/jQuery 实现此验证?也许是一个指令?我是 Angular 新手,非常感谢任何帮助,谢谢!

HTML:

<div ng-repeat="(index, val) in barcodes.barcodes track by $index">
  <div class="form-group row" ng-show="barcodes.barcodes[index]">
    <div ng-if="barcodes.barcodes[index] != 'X'">
      <label class="col-sm-3 form-control-label" style="margin-top:5px"> {{ barcodes.barcodes[index] }} </label>
      <label class="col-sm-2 form-control-label" style="margin-top:5px"> {{ barcodes.A_adaptors[$index+8] }} </label>
      <div class="col-sm-1" style="margin-top:5px">
        <button class="btn btn-xs btn-default hvr-pop" data-toggle="dropdown" ng-click="getIndex($index+8)"><i class="fa fa-cogs" aria-hidden="true" style="color:#DF3D42"></i></button>
          <ul class="dropdown-menu" role="menu">
             <div ng-repeat="x in barcodes.B_adaptors">
               <li class="text-center" ng-click="replace(x)" id="B_adaptors">{{ x }}</li>
             </div>
          </ul>
      </div>
      <div class="col-sm-6">
        <input type="text" class="form-control matching" ng-model-options="{ updateOn: 'blur' }" ng-model="item.barcodeInput" placeholder="Barcode" required>
        <div ng-show="!isEqualToBarcode($index+8, item.barcodeInput)"> Error: Barcode not the same! </div>
      </div>
    </div>
  </div>
</div>

JAVASCRIPT:(在控制器中)

$scope.isEqualToBarcode = function(index, val) {
    if(val === null || val === undefined) return true;

    if($scope.barcodes.A_adaptors[index] !== val.trim()) {
        console.log("wrong", val);
        alert("Incorrect Barcode, Try Again.");
        val = "";
    }

    return $scope.barcodes.A_adaptors[index] === val.trim();
}

【问题讨论】:

    标签: javascript jquery angularjs validation


    【解决方案1】:

    一种方法是将其更改为角形。 Angular 为无效输入提供输入验证和标志。 这是一个让你开始的链接 你也可以定义你自己的验证器指令。

    https://docs.angularjs.org/guide/forms

    【讨论】:

      【解决方案2】:

      这是因为 ng-show 期待一个布尔值,函数在 ng-show 中通常不会按预期工作。尝试将isEqualToBarcode 函数放在ng-blur 事件内的输入上。

      据说更好的解决方案是使用 Angular 的输入/表单验证,我简要解释了如何使用它 here 但如果您完全不熟悉,您可能需要查看文档或教程它。你想要的那种验证并不是开箱即用的,幸运的是other people have already created a custom directive to handle that。它用于确认密码,但基本功能仍然相同(匹配 2 个值)。这可能看起来很长,但相信我,从长远来看,它会为您省去很多麻烦。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 2015-09-20
        • 2018-11-10
        • 1970-01-01
        • 2014-09-30
        • 1970-01-01
        相关资源
        最近更新 更多