簡體   English   中英

使用angular.js驗證輸入字段中的文本

[英]validate text in an input field with angular.js

我有一個字符串數組,可以稱它們為條形碼。 我正在使用Angular.js遍歷此數組並顯示字符串和輸入字段。 我需要使用angular來驗證,當用戶在此輸入字段中輸入新條形碼時,該條形碼與旁邊顯示的字符串相同,請參見下面的示例。 我現在正在嘗試一個ng-change事件,如果它只是一個輸入字段,該事件將起作用,但是由於我使用的是ng-repeat,因此無法完成該工作。 我猜我需要建立一個指令? 我是新來的有角度的人,所以任何幫助或建議都很棒。 謝謝!

條碼

編輯:

出於我的目的,如果用戶輸入錯誤,我需要提醒他們。 我的情況是唯一的,因為用戶將不會在輸入字段中鍵入..他們將使用條形碼掃描儀,因此從本質上講,它與復制/粘貼相同。 下面的@KKKKKKKK回答使我很接近。 我進行了一些微妙的更改(如下),但是現在引入了其他錯誤。 使用下面的代碼,我會收到正確的警報消息,但是會觸發三遍? 我不知道為什么。

HTML:

<input type="text" class="form-control matching" ng-model-options="{ updateOn: 'blur' }" ng-model="item.barcodeInput" placeholder="Barcode">
<div ng-show="!isEqualToBarCode($index, item.barcodeInput)"> Error: Value not the same! </div>

在Angular Controller中:

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

只需將$index傳遞給命令,然后將其與數組進行比較即可。 (對不起,編碼錯誤)

控制器:

$scope.isEqualToBarCode = function(index, val) {

    //if val is empty, don't display error
    if(val === null || val === undefined) return true;

    return $scope.barcodeArray[index].barcodeVal === val.trim();
}

HTML:

<div ng-repeat="item in barcodeArray">
    {{item.barcodeVal}}

    <input ng-model="item.barcodeInput" ng-model-options="{ updateOn: 'blur' }" />

    <div ng-show="!isEqualToBarCode($index, item.barcodeInput)">
        Oh no!  Value not the same!
    </div>

</div>

如果要基於輸入的值設置表單有效性,則可以,您需要編寫一個自定義指令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM