0

I am currently trying to validate a card with AngularJS. This works fine until the user deletes all the inputted data from the input field, then it throws the following errors:

angular.js:11004 undefined is not an object (evaluating '$scope.card.length')

My HTML Code:

<input type="text" class='form-control' id='card' ng-model="card" ng-change="validateCard()" required>

JavaScript code that throws the error when the input is empty:

$scope.validateCard = function() {
    // Get card type
    if ($scope.card.length) { // <-- throws the error
        [...]

I also tried

if ($scope.card.length !== undefined) {

but it didn't help.

2
  • $scope.card might as well be undefined. if($scope.card && $scope.card.length) maybe? Commented Apr 11, 2017 at 9:08
  • 1
    if ($scope.card && $scope.card.length) ... Commented Apr 11, 2017 at 9:08

3 Answers 3

2

Thats because you cannot take length of undefined value. You could use something like this:

if ($scope.card && $scope.card.length) { }
Sign up to request clarification or add additional context in comments.

Comments

0

You can check for both using && condition

$scope.validateCard = function() {
   if ($scope.card && $scope.card.length) { 
}

Comments

0

Just check that your item is defined:

if (angular.isDefined($scope.card) && $scope.card.length) { }

Comments

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.