The Angular JS validation feature does not seem to be functioning correctly when used in conjunction with Bootstrap's

I'm currently working on a form that utilizes AngularJS and Bootstrap for validation. Everything was functioning properly until I introduced typeahead functionality - the validation no longer triggers when selecting values from typeahead.

Is there a way to ensure that the field still validates even when using typeahead?

See it in action: View JS Fiddle Here

Code Snippet:

<div ng-app="myApp" ng-controller="myCtrl">
    <form action="" name="myForm">
        <input type="text" name="one" ng-model="one" ng-valid-func="validator" />
        <div class="warning" ng-show="!myForm.one.$valid">
            <i class="icon-warning-sign"></i> One needs to be longer
        </div>
        <input type="text" name="two" ng-model="two" ng-valid-func="validator" class="typeahead" />
        <div class="warning" ng-show="!myForm.two.$valid">
            <i class="icon-warning-sign"></i> Two needs to be longer
        </div>
    </form>
</div>

Additional CSS Styling:

input.ng-invalid{
    background-color: #fdd !important;    
}

input.ng-valid{
    background-color: #dfd !important;    
}

Extra JavaScript Code:

var app = angular.module('myApp', [])

var myCtrl = function($scope){

    $scope.one = ""
    $scope.two = ""

    $scope.validator = function(val){
        return val.length > 3
    }

}

$(function(){
    $('.typeahead').typeahead({
        source: ['animal','alphabet','alphabot!','alfalfa']
    })
})


app.directive('ngValidFunc', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (attrs.ngValidFunc && scope[attrs.ngValidFunc] && scope[attrs.ngValidFunc](viewValue, scope, elm, attrs, ctrl)) {
          ctrl.$setValidity('custom', true);
        } else {
          ctrl.$setValidity('custom', false);
        }
        return elm.val()
      });
    }
  };
});

Answer №1

As mentioned by alfrescian, AngularJS offers a typeahead feature.

You can check out the demo on Fiddle.

While there are still some issues to address, it seems to align with your requirements.


<div ng-app="myApp" ng-controller="myCtrl">
<form action="" name="myForm">
    <input type="text" name="one" ng-model="one" ng-valid-func="validator" />
    <div class="warning" ng-show="!myForm.one.$valid">
        <i class="icon-warning-sign"></i> One needs to be longer
    </div>
   <input type="text" ng-model="two" ng-valid-func="validator" typeahead="suggestion for suggestion in option($viewValue)"/>
    <div class="warning" ng-show="!myForm.two.$valid">
        <i class="icon-warning-sign"></i> Two needs to be longer
    </div>
  </form>   
</div>

Your JS


var app = angular.module('myApp', ['ui.bootstrap'])

var myCtrl = function($scope, limitToFilter){

$scope.one = ""
$scope.two = ""

 $scope.option = function(value) {
       console.log(value);    
  return limitToFilter($scope.options, 10);   
 };

$scope.options = ['animal','alphabet','alphabot!','alfalfa'];   


$scope.validator = function(val){
    return val.length > 3
}

$scope.run = function(value){
    console.log(value);
};             

}

app.directive('ngValidFunc', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
  ctrl.$parsers.unshift(function(viewValue) {
    if (attrs.ngValidFunc && scope[attrs.ngValidFunc] && scope[attrs.ngValidFunc](viewValue, scope, elm, attrs, ctrl)) {
      ctrl.$setValidity('custom', true);
    } else {
      ctrl.$setValidity('custom', false);
    }
    return elm.val()
  });
  }
 };
});

I hope this information proves helpful in resolving any challenges you may be facing.

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

Struggling to find a solution to adjust an Angular directive

I am attempting to create a functionality where, upon clicking a button, the user can select one of two images displayed and make the selected image draggable. Currently, my code displays two images with only one being draggable. I am struggling to impleme ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

The container is not showing the JSTree as expected

My current project in JavaScript involves integrating a JSTree structure, but I'm encountering an issue where the tree is not showing up or rendering within its specified parent container. Below is the snippet of code I have been using to attempt to d ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

How to retrieve JSON data from ASP.NET code-behind file and pass it to JavaScript

I'm facing an issue with my webstatic method that converts my dataset into JSON. I want to retrieve this JSON in my JavaScript file, but unfortunately nothing is appearing in my div. As a newcomer to ASP.NET and JSON, I must be doing something wrong h ...

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...

Maintain aspect ratio and position of Three.js on canvas resize

Currently, I have a div that includes a three.js canvas. My goal is to maintain the ratio and position of the content within the canvas when its size changes. https://i.sstatic.net/ZOj9n.png I have attempted the following: window.addEventListener(' ...

Having trouble getting CSURF (CSRF middleware) to function properly with XSRF in AngularJS

Struggling to get the CSRF middleware working with Express and Angular? You're not alone. Despite various guides on the internet, the process remains unclear. Express 4.0 uses csurf as its CSRF middleware, while Angular requires setting X-XSRF-TOKEN. ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...

My chat in an Iframe does not seem to reload the content when the user navigates to a different page

I am currently facing an issue with a chat feature on my website that is displayed within an iframe. The chat itself is hosted on chat.A.com, which is on a different server than my site (A.com). To embed the chat on A.com, I am using an iframe with the s ...

What is the procedure for eliminating an event listener that does not directly invoke a function?

I have implemented an event listener in my JS file following a successful AJAX request: var pageButtonsParentElement = document.getElementById("page-buttons"); pageButtonsParentElement.addEventListener('click', event => { ...

Error - Oops! It seems like there was a TypeError that occurred because the property 'innerHTML' cannot be set for something that

I keep encountering this issue in my code. Uncaught TypeError: Cannot set property 'innerHTML' of undefined Despite trying various suggestions from other posts with similar errors like Uncaught TypeError: Cannot set property 'innerHTML&apos ...

Execute an HTTP POST request to the Node server, sending an empty object

For my project, I am attempting to send an HTTP Post request to my Node server from an html form. Despite using Body Parser and setting it up correctly, I am facing an issue where the req.body on my server is returning as an empty object. Can anyone prov ...

Is there a way to implement a function in Javascript or CSS where hovering over a button will cause a div to scroll either left or right

I am working on creating a unique photo gallery layout with a description block positioned below the images. My goal is to incorporate two arrow buttons, one on each side of the photos, that will trigger a scrolling effect when hovered over - shifting the ...

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

How can we pass props conditionally and ensure they are not undefined when using React useHistory for navigation?

In component1, I am redirecting the user to another page while passing props in the following way: onClick={() => history.push({ pathname: "/student/planandprice", state: { plan: history.plan.courseName, as: history.availableSession } })}& ...

How do I use jQuery to make a div appear when the previous one closes?

I've been experimenting with some code and it's gotten pretty lengthy. It works fine with just a few divs, but what if I need to implement this on 20 or more...? Is there a way to condense the code I've written? (I'm still new to jque ...