Having trouble with ng-class validation not functioning correctly in AngularJS?

I attempted to implement a green background for edited and valid input.

However, it seems that even for invalid input, the background remains green. Ideally, invalid input should trigger a yellow background with red text.

I would greatly appreciate any assistance in resolving this issue.

HTML

<div ng-app="myApp" ng-controller="formCtrl">

    <form name="inputform">
        <div ng-class="{'has-success': inputform.email.$dirty && inputform.email.$valid, 'has-error': inputform.email.$dirty && inputform.email.$invalid}">
            <label for="exampleInputEmail1">Email</label>
            <input type="text" name="email" ng-model="data.email" id="exampleInputEmail1" />
        </div>
    </form>

    {{data}}

</div>

Javascript

var module = angular.module("myApp", []);

module.controller("formCtrl", ['$scope', function($scope){

    $scope.data = {};

}]);

CSS

.has-error {
    color: red;
    background-color: red;
}

.has-success {
    color: black;
    background-color: green;
}

Answer №1

The input element lacks any validation constraints, making it perpetually valid. To witness validation in action, test the form below where I have implemented required and email validations:

(The input will only turn green upon entering a correct email address)

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

app.controller("formController", ['$scope', function($scope){

    $scope.formData = {};

}]);
.error {
    color: red;
    background-color: red;
}

.success {
    color: black;
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="formController">

    <form name="inputForm">
        <div ng-class="{'success': inputForm.email.$valid, 'error': inputForm.email.$invalid}">
            <label for="inputEmail">Email</label>
            <input type="email" name="email" required ng-model="formData.email" id="inputEmail" />
        </div>
    </form>

    {{formData}}

</div>

You may also explore this library for streamlined Bootstrap form validation.

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

Checking JSON formatted actions in Rails 4: A guide to testing

I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController # POST /users.json def create @user = User.new(user_params) respond_to do |format| ...

Endless Angular Scrollability

I am currently incorporating this plunker example into my application http://plnkr.co/edit/p6Dt3yvTq40Vn56AKiqC?p=preview. Here is the client-side code: $scope.fetch = function($select, $event) { if ($scope.loading) { return; } // no eve ...

jQuery UI tabs loaded with Ajax causing Javascript to malfunction

It appears that Javascript is disabled in jQuery UI tabs when loaded through ajax. Testing with jQuery tooltips and .click() alerts shows that Javascript functions properly in tabs not loaded through ajax (IDs present on the page). Below is the method use ...

Ways to swap out an img element with an almost identical gif element while maintaining its precise placement consistently

I am facing an issue in my code where a random element is generated within the body and when clicked, it is replaced with another gif element. I am using offset() to obtain the top and left values of the original image, and then using replaceWith() to swap ...

Removing an object from the scene using three.js

Is there a way to remove an object from a three.js scene? I am trying to delete a cube when a specific key is pressed, but so far I can only clear the entire scene instead of removing just one cube. ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

String arrays in Javascript with arithmetic operators

I am working with an array that contains mathematical signs. var signs = ['+', '-', '*', '/']; In addition, I have two variables representing digits to combine with each sign from the array. var right_digit = 1; v ...

What is the best way to delete a nested child object using a specific identification number?

Here is the current json structure: $scope.dataList = [{ CompanyName: null, Location: null, Client: [{ ClientId: 0, ClientName: null, Projects:{ Id: 0, Name: null, } }] }]; I'm attempting to remo ...

How can I efficiently preserve JSON data in Node.js without overflowing my storage capacity?

The headline pretty much says it all. I created a Discord bot with a ranking system that stored data in my filesystem. Unfortunately, as more users joined, my storage space became increasingly limited. I'm wondering if there's a way for me to ut ...

I am encountering a confusing issue where utilizing await does not actually wait for a Promise to resolve. Can you shed some light on why this unexpected behavior is happening?

Here is a function that I am working with: const getCurrentDetails= async () => { const currentDateTime = new Date(moment('00:00','HH:mm') .tz('America/New_York') ...

Preventing grid-collection from iterating within a for loop in Liquid on Shopify

I am trying to find a solution to prevent the grid-collection div from iteratig inside a for loop. Below is a snippet of my code in liquid: {% for block in section.blocks %} {% if block.settings.download_title %} <div class="title& ...

Utilize D3.js to display topoJSON data on your website

My project involves creating a visualization of the India map using d3 and GeoJSON. However, I am facing difficulties in properly displaying each Indian state on the map. Any assistance in identifying and resolving the issue would be greatly appreciated. T ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

Loop through the mongoose object using EJS

When I insert <%= products %> into my view, it displays [Object Object], indicating that the mongoose resultset is an object. However, when I attempt to iterate over the products object, I receive an error stating products.forEach is not a function. ...

Is there a method to disregard acronyms when using title case formatting?

Query Background I currently have a compilation of TV shows that I am looking to convert into title case format. While my current code performs well on titles such as "Bojack Horseman," "Family Guy," and "Jessica Jones," it encounters difficulties with ac ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Attempting to extract a parameter from a URL and pass it as an argument to a function for the purpose of locating objects based on

I am trying to retrieve data from a URL http://localhost:3000/share/user=sampleuser to display objects with an author value that matches the one in the URL. However, I encountered an error when attempting to call a function that extracts the value from t ...

Displaying temporary data and removing it from an HTML table: Tips and Tricks

There are three input boxes and a button below them. When the button is clicked, I would like the input data to appear in an HTML table where I can delete records. I would greatly appreciate any assistance. Thank you in advance. ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...