0

I have an array of strings, lets call them barcodes. I’m using to Angular.js to loop through this array and display the strings and a input field. I need to use angular to validate that when a user enters a new barcode into this input field that it’s identical to the string that’s displayed right next to it, see example below. I attempting a ng-change event right now which would work if it was just one input field, but because I’m using ng-repeat I cannot make that work. I’m guessing I need to build a directive? I’m new with angular so any help or suggestions would be great. Thanks!

barcode

EDIT:

For my purpose I need to alert the user if they enter an incorrect input. My case is unique as the user will not be typing in the input field.. they will be using a barcode scanner, so essentially it is the same as a copy/paste. @KKKKKKKK answer below gets me very close. I made some subtile changes (below) but now this introduces other bugs. with this code below I get the proper alert message but it fires three times? I cannot figure out why..

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>

In 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();
}

1 Answer 1

2

Just pass in the $index to your command and then compare it to your array. (Sorry for blind coding errors)

Controller:

$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>

If you want to set the form validity based on inputted values, then, yes, you would need to write a custom directive.

Sign up to request clarification or add additional context in comments.

1 Comment

Great Answer, exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.