New to Angular: Struggling with complex form validation?

I am just starting to explore Angular and I want to tackle some more advanced input validation.

My task involves a table where each row has three text inputs. I need to validate that at least one row has three non-empty input fields. If this criteria is met, I need to display a message.

I'm a bit stuck on how to cleanly achieve this in Angular. Any guidance or assistance would be greatly appreciated.

Here is a snippet of 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 my controller looks like this:

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

You can see the issue in action in this plunker: http://plnkr.co/edit/Ws3DxRPFuuJskt8EUqBB

Answer №1

Speaking truthfully, I wouldn't categorize this as form validation. It would be more straightforward if you utilized a real model to observe, rather than an array in the template. The approach you initiated could potentially lead to manipulation of the DOM within the controller, which is not recommended for Angular.

An initial sketch with a model could look like this:

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) {
    // update `haveCompleteRow` based on changes in rows
    $scope.haveCompleteRow = rows.some(function (col) {
      return col.every(function (cell) {
        return cell.text.length > 0;
      });
    });
  }, true);
}]);

Include the following in your template:

<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>

See the demo: http://jsbin.com/URaconiX/2/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

How to pass a method from a child component to a parent component in Vue.js

Does anyone know how to pass a function from the child component to the parent component? I have a modal in the parent component with cancel and submit buttons. When either button is clicked, I want to close the child component. I tried setting "show" in t ...

Understanding how to open a PNG file in the client-side browser and transform it using PNGJS in React

Utilizing React JS for my application development is a current focus of mine. I have a solid understanding of how to import images within the client/browser folder structure. For example: import maze_text from '../../mazes/images/maze_text.png&apos ...

React JS Bootstrap Dropdown Troubleshooting

I'm facing a challenge in my React.js project while trying to implement a filter. The issue is that the list appears when I click on the button, but it doesn't disappear on the second click or if I click outside the list. Initially, I imported t ...

What is the best way to organize nestedGroups in the vis.js timeline?

Running into an issue with the nestedGroups in my code. Despite sorting the array before creating the items and nestedGroups, I'm encountering a problem where the first item is showing up in the last position on the timeline. https://i.sstatic.net/Ne ...

Using Node.js to execute JavaScript with imported modules via the command line

Having limited experience with running JavaScript from the command line, I am facing a situation where I need to utilize an NPM package for controlling a Panasonic AC unit, which includes a wrapper for their unofficial API. My objective is to create a sim ...

Dividing the array into distinct subarray groups

I am working with a JavaScript array that contains strings, like this: let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e&quo ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...

Comparison between forming JavaScript objects using arrow functions and function expressions

What is the reason behind const Todos = function () { ... } const todos = new Todos(); running smoothly, while const Todos = () => { ... } const todos = new Todos(); results in a TypeError: Todos is not a constructor error? ...

Transmitting video through a local area network

I am seeking a solution to stream video content to a local network with potentially over 1000 viewers. The streaming will need to be accessible via web browsers such as Internet Explorer, Chrome, and Firefox, as not all users have internet access due to co ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...

Enhancing the AngularJS Login feature for server authentication

Struggling to adapt Valerio Coltrè's Angular login example on GitHub to work with my ServiceStack authentication. Despite appreciating Valerio's implementation of authentication, I am facing challenges as he uses an httpBackend mock and interce ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

Angularjs scope's parent id

I'm looking to access or manipulate a scope's grandparent without making things overly complicated. Leveraging the controller as syntax, I can reference the parent controller like so: this.applicationCtrl.something with applicationCtrl > paren ...

"Transferring cart controller information to the checkout controller: techniques and best practices

As a beginner using MySQL as a backend to store data, I am struggling with passing product_id, quantity, and price to the checkout page. Can someone provide guidance on how to store these data efficiently? Cart Service .factory('sharedCartService ...

Include the document when the query results in zero documents

Struggling to figure out how to add a document to a collection if a query returns no results. The current query lacks operators for checking the length or size of the result. How can this be achieved? The query in question: this.monthCollection = this.af ...

Implementing Ui-Select: Enhancing functionality with a static footer directive

I am currently working on Ui-Select. My current task is to add a static button or text with a link as a footer inside the ui-select, displaying the level of match with the entered text. I am facing difficulties in getting my footer directive to only show ...

Progress bar indicating the loading status of an AJAX script

I am facing a challenge with creating a progress bar in AJAX. The entire page is loaded through AJAX, and one of the webpage elements uses AJAX to fetch large rows from the database. I have attempted to implement a progress bar within this script using a ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...