Mrutyunjaya Mohapatra Mrutyunjaya Mohapatra - 3 months ago 9
AngularJS Question

Validate a textbox input with an array list in angularjs

I am very new to AngularJS and currently I am working on a form which is designed in angularjs.

My task is to validate a textbox input with a list. If the value entered in textbox is not present in the list then it should throw a validation error.

I have written the below lines of code for getting the list items through rest API:

app.factory("EatonScanningFactory", ['$http', function($http) {

var EatonScanningFactoryObj = {};
EatonScanningFactoryObj.GetToolMaxTimeList = function (columnName) {
return $http({

method: 'GET',

url: _spPageContextInfo.webAbsoluteUrl
+ "/_api/web/lists/getbytitle('Tool%20Max%20Time')/Items/"
+ "?$select=Text,Value&$orderby=Text&$filter=Title eq '" + columnName + "'",

headers: { "Accept": "application/json;odata=verbose" }

});
}


It will return the list items into an array.
The below lines of code are for accessing calling the above function:

var getToolId = EatonScanningFactory.GetToolMaxTimeList('ToolNumber');
var getMaxLife = EatonScanningFactory.GetToolMaxTimeList('MaxLife');


I am unable to proceed further as I am not sure how to validate if my text box input is available in the list or not.

Please help

Answer

Hi there here is a plausible solution as an example:

$scope.list = EatonScanningFactory.GetToolMaxTimeList('MaxLife');

Javascript (Native) Example:

function validateList() {
    var IsInList = false;
    for (var i = 0; i < $scope.list.length; i++) {

        if ($("#textbox").val() == $scope.list[i].listvalue) {
            IsInList = true;
            break;
        } 
    }

    return IsInList;
}

Angular Example:

$scope.validateFunction = function() {  
    angular.forEach($scope.list, function(value, key){
        var IsInList = false;

        if($("#textbox").val() == value.listvalue) {
            IsInList = true;
            break;
        }
    });

    return IsInList;
}

//Invoke the function like follow:
$scope.validateFunction();