The error notification for form validation is not displaying as anticipated

I am currently developing an application using angularjs and bootstrap. My goal is to create a simple form validation where all fields in the form must have values when the user clicks on the submit button.

For a demo, you can visit: https://plnkr.co/edit/aHtODbTTFZfpIRO3BWhf?p=preview In the provided demonstration, if a user tries to submit the form without selecting a checkbox, an error message stating 'Please Select the Color..' will be displayed. Even after selecting the checkbox and clicking on submit, the error message persists. Any insights on how to address this issue?

Here is a snippet of the HTML code:

<form name="myForm" ng-controller="ExampleController">
   <div>Select Color : </div>
      <label name="color" ng-repeat="color in colorNames" class="checkbox-inline">
<input ng-required="selectedColor.length === 0" oninvalid="this.setCustomValidity('Please select the color..')" type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)">                        <!--<input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}-->
     {{color}}       <br>       </label>

            <div class="">
                <div style="color: black;">Username : </div>
               <input type="text" name="user" value="" required>
                <div ng-show="myForm.$submitted || myForm.user.$touched">
                    <p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
                </div>
            </div>            
             <button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
 </form>

Answer №1

Initially I have defined an array to store the values of checkboxes:

$scope.selectedColor = [false,false,false];

Next I implemented a method for checkbox validation:

$scope.someSelected = function () {
           for(var i = 0; i < $scope.selectedColor.length; i++) {
             if($scope.selectedColor[i]) return true;
           }

           return false;
};

Thirdly I utilized ng-model to update the HTML code, enabling two-way data binding for synchronized updates between view and controller:

<input ng-required="!someSelected()" ng-model = "selectedColor[$index]"  type="checkbox" name="color" value="{{color}}">

Fourth step The user input box lacked the ng-model, causing changes in the view not to reflect in the controller. I resolved this issue by adding ng-model.

<input type="text" ng-model = "user" name ="user" value="" required>

Fifth point I updated the form submission validation logic:

$scope.submitForm = function(){
             if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) {
          alert("all fields are entered");
            }else{

            }
        }

That's all!

Please test the modified code snippet below:

Answer №2

To resolve the issue, remember to make adjustments in (1) color input field, (2) user input field, and (3) submitForm function.

<input ng-required="selectedColor.length === 0" onchange="this.setCustomValidity(!validity.valueMissing && '')" oninvalid="this.setCustomValidity(validity.valueMissing ? 'Please select the color..' : '')" type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)">

<input type="text" name="user" value="" ng-model="user" required>

$scope.submitForm = function(form){
  if ($scope.selectedColor.length > 0  && $scope.user != "") {
    console.log('All fields have been filled out');
  } else{

  }
} 

(1) Make sure to handle the checkbox when it is selected correctly.

(2) Link the $scope.user object with the input by setting ng-model=user for the user input field.

(3) Verify that the selectedColor array contains at least one item and the user field is not empty in the submitForm method.

Lastly, ensure your code is properly formatted with linting and indentation for better readability.

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

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

a guide on configuring a default input value from a database in a React component

In my current project, I have an input field with the type of "checkout" and I am looking to utilize Firestore to retrieve a default value. Once I obtain this value, I plan to store it in the state so that it can be modified and updated as needed. Here i ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

Precise coordination of a singular model through the use of angularFireCollection

I am currently using version 0.3.0 of angularFire in order to connect an AngularJS application to Firebase. My goal is to achieve explicit synchronization of a single model on an edit form. After referring to the documentation, I attempted to utilize angu ...

"Utilize JavaScript to assign array values to the main object for efficient data

I am looking to parse a modified JSON file to create separate objects for each team and player. I want each object to have a key for the team name and the player name. Using JavaScript, how can I achieve the following structure: [ { name: 'Dallas St ...

Empty placeholder image appearing at the beginning of JavaScript slideshow in Ruby on Rails

As a newcomer, I ask for your understanding if I lack knowledge in some areas. I have been working on a project and using the cycle2 plugin successfully to create a slideshow on my index page with images pulled from the internet. Now, I am trying to impl ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

AngularJS is unable to properly show the full calendar on the screen

Currently working with fullcalender.js in conjunction with AngularJS. Encountering an issue where the calendar is not displaying without any error indication, making it difficult to identify the missing component. This marks my initial attempt at combinin ...

Creating a Higher Order Component in React that accepts another higher order component as a parameter

Currently, I am delving into the world of Material UI on my own and stumbled upon the HOC pattern method called withStyle HOC API. I decided to test it out by implementing a simple string style myself to grasp how this hoc (withStyle) function integrates w ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

Currently, I am expanding my knowledge of PHP and MySQL by working on a dynamic form that utilizes arrays. As I progress through the project,

One of my recent projects involved creating dynamic rows in a form using code. I managed to save the data in an array and display it using a foreach loop, but I'm facing challenges when trying to insert this data into a database. Here's a glimps ...

How to dynamically load content into a div on an ASP.NET website without needing to reload the

I have a situation where I am dynamically loading a popup div with various HTML page contents. While the HTML page controls are rendering on the div successfully, the issue arises when the entire page refreshes during the content load using $("#middlepart" ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Improve the performance of the search results page by prioritizing the retrieval of the number

I am facing an issue with the loading time for displaying more than 1000 rows of results in my code. Is there a way to modify the code to first check the number of query results and then create pagination before fetching only the results for that specific ...

Backbone.js struggles with rendering collection object fields when the JSON response is enclosed within a "book" domain wrapper

Upon receiving the following JSON data, the view and HTML code successfully renders the values on the webpage. JSON DATA [{"id":"1234","name":"book1","type":"catg1"},{"id":"1235","name":"book2","type":"catg1"}, {"id":"1236","name":"book3","type": ...

How do I adjust the amount of a product in my Django ecommerce store?

There seems to be an issue where the quantity is only being changed in the first product, even if I click on the arrow of the second product. The changes are reflected in the quantity of the first product instead. cart.js var changeQ = document.getElements ...

Jquery failing to append existing values into the DOM

I'm currently attempting to enhance an existing jQuery table structure with the following code snippet: function GetViewData(data) { $.ajax({ type: "GET", url: "/Services/Configuration/ViewServices. ...

WebRTC signalling has been successfully completed, however, the remote video functionality is still not functioning as expected

I attempted to set up webRTC and successfully negotiated the peerConnection. However, I am encountering an issue where remote videos are not playing. For more information, you can check the detailed console logs at this link - fb.privetbureau.com Here is ...

Steps to update the bootstrap version in an existing project

My current project was built using Bootstrap 3.3.6 classes, but now I want to take advantage of the features offered by Bootstrap 5.2. However, simply changing the version of Bootstrap isn't as easy as it sounds. What is the most effective way to upgr ...