简体   繁体   中英

Angular JS Form Validation

I'm working on an admin where users can add X amount of cells. Each cell consists of:

  • name
  • imageURL
  • destination link

User can bulk add cells (starts with 8, they could add 20 at once) or one at a time.

I need to validate each field to confirm that they are good. I had planned on using angular form validation for this. Unfortunately there is the requirement which states that should the user have X # of items, but only filled in half (leaves any entire cell empty) just disregard that cell as a whole.

The problem lies in that if there are 10 cells on load, the form (holds all the cells) is pristine / invalid. I fill in all 10 items, form is now dirty / valid. I add 5 more, form is dirty / invalid. fill out 2 of those cells and want to submit, form is still dirty / invalid when I would want it to be dirty / valid

Any thoughts on this?

Example plunkr: http://plnkr.co/edit/qwObH5LnxLvgJydJlJVS?p=preview

Bonus points on if I can do this without having to use a form tag.

I saw your example on plunkr.

Adding a delete button, the user can delete the rows that do not want to fill. So the form comes back to the dirty/valid state.

It sounds like you want empty rows to be valid, but empty input fields in a non-empty row to be invalid.

To achieve this, you can add conditional requirements to each field using ng-required , so that it is only required if there is at least some text elsewhere in the row.

From your plunkr, you can replace required with ng-required on each input:

<li ng-repeat="cell in cells">
    <input type="text" name="dest" ng-model="cell.dest" placeholder="Destination Link" ng-required="cell.src || cell.name"/>
    <input type="text" name="src" ng-model="cell.src" placeholder="Image Link" ng-required="cell.dest || cell.name"/>
    <input type="text" name="cellName" ng-model="cell.name" placeholder="Name" ng-required="cell.src || cell.dest"/>
</li>

To improve scalability, you could also define a method on the cell objects or the controller to evaluate whether a cell object is blank:

function cellCtrl($scope) {
    ...
    $scope.isBlankCell = function(cell) {
        ...
    }
}

and call that method from the template:

<li ng-repeat="cell in cells">
    <input type="text" name="dest" ng-model="cell.dest" placeholder="Destination Link" ng-required="isBlankCell(cell)"/>
    <input type="text" name="src" ng-model="cell.src" placeholder="Image Link" ng-required="isBlankCell(cell)"/>
    <input type="text" name="cellName" ng-model="cell.name" placeholder="Name" ng-required="isBlankCell(cell)"/>
</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM