bespoke validation using AngularJS

Consider a scenario where there is a table comprising of 10 rows and each row contains 10 columns of checkboxes.

Prior to the user submitting the form, it is necessary to implement a validation rule: at least two checkboxes must be checked in each row!

<form name="myForm">
    <div data-ng-controller="myController">
        <table border="1">
            <tr>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
                <td><input type="checkbox" /></td>
            </tr>
            ...
        </table>

        <button data-ng-click="save()" ng-disabled="$myForm.invalid">Save</button>
</form>


$scope.save = function() {
    if (myForm.$valid){
        alert("can submit the form...")
    }
};

How can this be achieved? Where should the validation logic be incorporated?

Answer №1

Just recently, I came up with a unique solution to a question similar to this one. By creating a custom directive, users can now specify groups of controls like text-fields, selects, and checkboxes, requiring at least one control in each group to be filled out.

This solution is easily customizable to require that at least two controls are filled out instead. This way, the validity of myForm.$valid will always reflect the current state, making it useful for providing visual feedback or enabling form submission confidently.

Answer №2

If you have checkboxes set in the HTML that do not change, one solution is to link them to boolean models like so:

<input type="checkbox" ng-model="checked[1]">
<a href="javascript:;" data-ng-click="validate()">Validate</a>

Then you can use the following code for validation:

$scope.checked = {};
$scope.validate = function() {
  var count=0;
  angular.forEach($scope.checked, function(k,v){ if (k) count++; });
  if (count > 2)
      alert("validated");
};      

This approach can easily be extended to multiple rows.

You can see a working example here: http://plnkr.co/edit/thbJ81KWUDyF6WTcWL9u?p=preview

Additionally, you have the option to define an array in the controller and utilize the ng-repeat directive in combination with this method.

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

"The FindByIdAndUpdate function is successfully updating the data, but it is unexpectedly

This is my first time seeking guidance here, as I've reached a dead end with my issue. I am currently working on a household collection that includes a member collection within it. Whenever new members join, I need to update the household collection ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

Troubleshooting problems with AJAX function in the .each() loop

My webpage showcases a grid layout with 16 blocks arranged in 4 columns and 4 rows. As you scroll to the bottom of the page, an AJAX function dynamically loads another set of 16 blocks each time. To enhance user experience, I wanted to implement a smooth ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

Ways to verify multiple radio groups to ensure none have been left unchecked

https://i.sstatic.net/EoE1A.png Is there a more elegant solution to check if either "salad" or "side dish" is left unchecked after submission? I currently have a working approach, but it feels overly complex for such a simple task. This is my current me ...

preventing ng-click functionality on an element that is not a button

In order to present a series of answer choices, I am utilizing <p> tags. These choices are designed to be selectable, triggering the activation of a class and execution of specific functions upon selection. My objective is to prevent any ng-click ac ...

What is the best way to capture a 403 response when making a GraphQL API call?

My server handles component rendering and generates an HTML response upon request. During the rendering process, the server initiates a GraphQL call for a specific component which sometimes results in a 403 error. Here is the code snippet: const client = ...

Using Google Script Code in Sheet to input a key and click on the submission button

Is there a way to enable using the Enter key in addition to clicking the submit button to input data and save it to a cell? I'm having trouble getting my current code to work. Any suggestions on how to modify it? <script> var itemBox = document ...

Mouse hovering over the JS slider activates the sliding functionality, while removing the cursor

Hi there, I'm encountering some issues with the JS clients slider on my website. I need to pause it when the mouse is over and resume when the mouse leaves. I've double-checked the code but for some reason it's still not functioning properl ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

The return value cannot be retrieved from a promise function in Node

I'm facing an issue where the return value of a certain function is being executed before the actual result is returned. Can anyone provide guidance on how to solve this? Thanks! exports.addUser = async (data) => { const updateduser = await db.U ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...

Navigating with AngularJS and jQuery Mobile

Currently I am developing a web application utilizing jQuery and jQuery-Mobile, however there has been a request for me to incorporate AngularJS into the project. The issue I am facing primarily involves handling routing within the application, despite res ...

React Native buttons are displaying at a fixed width and not adjusting as expected

Within a row, I have two buttons with a padding of 20 between them, and they are only taking up the necessary width for the button text. The width remains constant! Here is the code for the buttons: <View style={styles.buttonContainer}> &l ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

How to retrieve a value from ng-options using AngularJS?

I want to display a dropdown in which users can select a specific month. Currently, the dropdown is populated with all 12 months in an array. How can I make sure that only the selected month is fetched from the dropdown? Code Snippet: $scope.Month = [&ap ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...