Richard
Richard

Reputation: 65550

Angular newbie: non-trivial form validation?

I am new to Angular, and I would like to do some non-trivial input validation.

Basically I have a table. Each row contains three text inputs. When the user types into any text inputs, I would like to check whether the table contains at least one row with three non-blank input fields. If it does, I want to show a message.

I have no idea how to do this cleanly in Angular, any help would be much appreciated.

This is my HTML:

<tr data-ng-repeat="i in [1,2,3,4,5]">
  <td data-ng-repeat="i in [1,2,3]">
    <input ng-model="choice.selected" ng-change='checkAnswer(choice)' type="text" />
  </td>
</tr>
... 
<div ng-show="haveCompleteRow">we have a complete row!</div>

And controller:

$scope.haveCompleteRow = false;
$scope.checkAnswer=function(choice){
  $scope.haveCompleteRow = true; // what to do here?
}

Here is a plunker demonstrating the issue: http://plnkr.co/edit/Ws3DxRPFuuJskt8EUqBB

Upvotes: 0

Views: 93

Answers (1)

Yoshi
Yoshi

Reputation: 54649

To be honest, I wouldn't call this form validation. But for starters, it would be a lot simpler if you had a real model to observer, instead of an array in the template. The way you started will, or at least could, lead you to dom-manipulation inside the controller, which is a no-go for angular.

A simple first sketch with a model could be:

app.controller('TestCtrl', ['$scope', function ($scope) {
  $scope.rows = [
    [{text: ''}, {text: ''}, {text: ''}],
    [{text: ''}, {text: ''}, {text: ''}],
    [{text: ''}, {text: ''}, {text: ''}]
  ];

  $scope.haveCompleteRow = false;

  // watch for changes in `rows` (deep, see last parameter `true`).
  $scope.$watch('rows', function (rows) {
    // and update `haveCompleteRow` accordingly
    $scope.haveCompleteRow = rows.some(function (col) {
      return col.every(function (cell) {
        return cell.text.length > 0;
      });
    });
  }, true);
}]);

with:

<body ng-controller="TestCtrl">
  <table>
    <thead>
      <tr>
        <th>Col1</th>
        <th>Col2</th>
        <th>Col3</th>
      </tr>
    </thead>

    <tbody>
      <tr data-ng-repeat="row in rows">
        <td data-ng-repeat="cell in row">
          <input ng-model="cell.text" type="text" />
        </td>
      </tr>
    </tbody>
  </table>

  <div ng-show="haveCompleteRow">we have a complete row!</div>
</body>

as the template.

Demo: http://jsbin.com/URaconiX/2/

Upvotes: 3

Related Questions