havenchyk havenchyk - 4 days ago 4
Javascript Question

How to validate table row data with Angular?

I have

table
with
ng-repeat
for table rows. I want to make inline editing and validation of data from single row, but it is impossible to use
form
or
ng-form
inside table.
For inline editing I use inputs with
ng-show
inside
td
.
So, I have two questions:


  1. Is it correct approach for inline editing? (using hidden inputs
    inside td).

  2. How can I validate data from row?



Update: I want for table row something like "form submitting" and add error class for table cells with wrong data.

I'm new to angular.

Answer

I create example with simple validation to your second question:

View:

<div ng-controller="MyCtrl">
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>Id</th>
                <th>Firstname</th>
                <th>Lastname</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.id}}</td>
                <td><input ng-model="item.firstName" ng-class="{ error: !item.firstName }"/></td>
                <td><input ng-model="item.lastName" ng-class="{ error: !item.lastName }"/></td>
                <td><input ng-model="item.email" ng-pattern="emailRegExp" ng-class="{ error: !item.email }"/></td>
                <td><button ng-disabled="!item.lastName || !item.firstName || !item.email"/>Submit</td>
            </tr>
        </tbody>
    </table>
</div>

Controller:

function MyCtrl($scope) {
    $scope.items = [
        {
            id: 1,
            firstName: 'Ivan',
            lastName: 'Ivanov',
            email: 'email@email.com'
        },
        {
            id: 2,
            firstName: 'Petr',
            lastName: 'Petrov',
            email: 'email@email.com'
        }
    ];

    $scope.emailRegExp = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; 
}

Please, see jsfiddle :)

Jsfiddle

For your question in comment about date validation:

I see two ways for do it:

1) In yor controller you create $scope.dateRegExp = "/^\d{2}([./-])\d{2}\1\d{4}$/" and into the view you using it with ng-pattern="dateRegExp"

2) You can use ng-change="" directive:

View:

<tr ng-repeat="item in items">
    <td><input ng-model="item.date" ng-change="validateDate(itemDate)" ng-class="{ error: dateInputError }"/></td>

Controller:

$scope.dateInputError = false;

$scope.validateDate = function(date) {
   if(//some validation){
      $scope.dateInputError = true; //true - it means error style shows
   }
};