Checking the validity of forms in Angular JS

I am currently developing an admin interface where users have the ability to add a specified number of cells. Each cell contains details such as name, imageURL, and destination link.

  • name
  • imageURL
  • destination link

Users can add cells in bulk (starting with 8 but up to 20 at once) or individually.

The challenge I am facing is validating each field to ensure they are properly filled out. My initial plan was to use Angular form validation for this process. However, a requirement states that if a user has a certain number of items but only fills in half of them (leaving an entire cell empty), that cell should be disregarded entirely.

The issue arises when there are already 10 cells loaded - the form (containing all cells) is considered pristine/invalid. Once I fill in all 10 items, the form becomes dirty/valid. Adding 5 more cells makes the form dirty/invalid. Even after filling out 2 of those new cells, the form remains dirty/invalid when ideally it should be dirty/valid.

Any insights on how to address this situation?

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

Extra credit if a solution can be implemented without using a form tag.

Answer №1

If you want to allow empty rows but make sure that input fields in a non-empty row cannot be left blank, you can set conditional requirements for each field using the ng-required directive. This way, the field will only be required if there is some text present in another part of the row.

In your plunkr code, simply replace required with ng-required for each input element:

<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 make this process more scalable, consider defining a function on either the cell objects or in the controller that checks if a cell object is empty:

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

Then, you can use this function in the template like so:

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

Answer №2

After coming across your example on plunkr, I got inspired.

By incorporating a delete button, users have the ability to remove unwanted rows and return the form to a dirty/valid state.

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

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

Changing knockoutJS foreach binding dynamically

I have a list of arrays known as table#1, table#2, ... table#10 and I want to be able to click on a table number and display the list items of that table in a panel. Here is a snippet of the code: The HTML part works fine. The only issue lies in this li ...

What is the best way to implement this ajax preloader?

<script type="text/javascript"> $(document).ready(function() { $('#loading') .hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); } ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

Click on an item in the list to remove it from the list

I am working with an object that contains multiple arrays of objects. I need help figuring out how to remove a single item from the list when clicked on. Although I know that using splice can achieve this, I'm unsure about implementing it in this spe ...

Facing a problem with model binding in Angular's scope?

Greetings! I am a beginner in AngularJS and currently working on developing a chat application for the Android platform using Socket.IO, AngularJS, and Ionic. However, I have encountered an issue with my chat page. I am attempting to connect the textbox to ...

Display or conceal the location where the click event occurs within a single div

progress $(".button-toggle").click(function(e){ $(this).parents.find('#second').toggle(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="first"> <a href="#" class= ...

In React, facing difficulty in clearing setTimeout timer

After clicking the button, I want my code to execute 3 seconds later. However, I'm having trouble achieving this. It either runs immediately or doesn't stop running. <Button onClick={setTimeout(() => window.location.reload(false), 4000), cl ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

Transmit information to Vue.js component

I am encountering an issue while attempting to transfer data from one component to another. Can someone provide assistance? Below is the code snippet: <template> <div class="q-pa-md" style="max-width: 900px"> <div v-if="fields.length" ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

how to change the color of a specific item in a list created using v-for

I'm a beginner when it comes to vueJs and I'm attempting to toggle the class "active" on a single element once it has been clicked. Currently, my code toggles all elements with the class material_icons. How can I modify it to toggle only the elem ...

Convert data into JSON format and exclude any unnecessary keys

I am encountering some challenges while trying to create a new array from existing Objects. If I execute the following code snippet: console.log(JSON.stringify(this.data)) The output is as follows: { "nodes":[ {"id":1,"node":"0","name":"pizz ...

The program is encountering an error message indicating the use of an undefined constant

I'm just diving into the world of angularjs and running into some roadblocks while trying to set up a basic checklist. <html lang="en" ng-app> <body> <div ng-controller="IdController" class="id-contain"> <ul> <li ng-r ...

ReactKonva does not have compatibility with the element type "div"

I am trying to create a circle with ReactKonva and display a tooltip when hovering over it. In React, we are required to return a single element from the render method. To achieve this, I attempted to wrap both the tooltip and the ReactKonva element within ...

Inserting an icon into a particular class

I am new to JavaScript and I am eager to understand the code I write rather than just using it. That's why I'm turning to this forum with a question regarding adding an icon to a colored group. Here is the code snippet I have: <strong> ...

jQuery is able to retrieve all the table data (TD) elements within a table

Using jQuery, I am extracting data from a table: $('#lc_searchresult > table > tbody > tr').each(function() { var data = $(this).find("td:eq(5)").html(); alert(data); }); It works well when the TR tag contains only one ...

Ways to boost memory capacity in nodejs

I've been attempting to increase the memory limit in node.js, and to do so I added an environment variable. You can see how I did it here Unfortunately, it doesn't seem to be working as expected. I even tried using capital letters with no succe ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...