What is the best way to address ng-invalid and ng-pristine in Angular validation?

I am encountering an issue with angular validation.

My scenario is as follows:

  1. In a form, I have 2 textfields and 1 button.
  2. Upon page load, the button is disabled due to the ng-invalid status.
  3. When some text is entered in a textfield, the button becomes enabled.
  4. [Issue] However, when all text in a textfield is cleared using the delete key on the keyboard, the button remains disabled.
  5. This problem occurs when the "required" attribute is not used with the textfield.

I have provided a solution on jsfiddle

<div ng-controller="validationCtrl">

    <form name="xyzForm" novalidate>

    <input
        type="text"
        name="name"
        ng-model="xname"
        ng-class="{'has-error': xyzForm.name.$invalid && !xyzForm.name.$pristine}"
    />
    <input
        type="number"
        name="age"
        ng-model="xage"
        ng-class="{'has-error': xyzForm.age.$invalid && !xyzForm.age.$pristine && xyzForm.age.$dirty}"
    />

    <div>
       <button ng-click="submit()" ng-disabled="xyzForm.$invalid || xyzForm.$pristine">Submit</button>
       <span>invalid : {{xyzForm.$invalid}}</span>
       <span>pristine : {{xyzForm.$pristine}}</span>
    </div>

    </form>

</div>

Answer №1

If you prefer not to use the "Required" Attribute for both textfields, you can do so by utilizing the following code:

<div ng-app="appX">

<div ng-controller="validationCtrl">
                    <form name="xyzForm" novalidate>
                        <input
                            type="text"
                            name="name"
                            ng-model="xname"
                            ng-class="{'has-error': xyzForm.name.$invalid && !xyzForm.name.$pristine}"
                        />
                        <input
                            type="number"
                            name="age"
                            ng-model="xage"
                            ng-class="{'has-error': xyzForm.age.$invalid && !xyzForm.age.$pristine && xyzForm.age.$dirty}"
                        />
            <div>
                                    <button ng-click="submit()" ng-disabled="(xyzForm.$invalid || xyzForm.$pristine) || !xage || xname
==''">Submit</button>
            <span>invalid : {{xyzForm.$invalid}}</span>
            <span>pristine : {{xyzForm.$pristine}}</span>
            </div>
                    </form>
                </div>

</div>

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

What could be causing the delay in this script's execution?

I'm attempting to include a script at the beginning of my XBL file, however even the test below is not functioning. Any insight on why this might be happening? <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/x ...

What is the best way to implement a toggle effect for my specific situation?

I need assistance creating a toggle feature for my angular app. This is what I currently have: <div ng-repeat='item in items'> <div ng-click='toggle-{{item.number}} =!toggle-{{item.number}}> <span> ...

Creating Duplicates of a Component in React

I am looking for a way to render multiple instances of the same component. Let's take a look at the component that needs to be duplicated (this is just a placeholder example, not the actual component): import React from 'react'; function Du ...

React application with a layout design that adjusts and responds to various

One task is to display various components based on the device's width; Two possible approaches have been considered: Create a React Component that accepts multiple components for different widths (sm, md, xl). It will automatically determine the de ...

Learn the steps to import and utilize individual BootStrap 5 JavaScript Plugins

I am currently diving into the world of Bootstrap (v5.1.0) and gulp, but I'm a bit confused about how to import specific Bootstrap JavaScript plugins. I attempted to bring in only the modal plugin from Bootstrap, but encountered either a syntax error ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

Dynamic search form technology

My HTML view includes a search form and AJAX code to handle the form request $(document).ready(function() { console.log('Ready'); $('.search-wrapper').on('click', '#find-dates', function(a) { a. ...

What could be causing the bootstrap 4 col-md-3 block to shrink when using position fixed?

When working with Bootstrap 4, I encountered an issue where changing the block position from relative to fixed using a script caused the block to decrease in size. The script I used includes a .sticky class: .sticky { position: fixed !important; top: ...

Error encountered in Pokemon API: Trying to access property '0' of undefined

My current challenge involves accessing the abilities of my Pokemon, but I keep encountering a recurring error. In my project development using React hooks, I fetched data from the Pokemon API and stored it in setWildPokemon. Utilizing wildPokemon.name suc ...

I am encountering an issue where the parameters I am sending through a POST request in Node.js

server.js: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); loggedIn = {}; app.use('/',express.static('www')); // static files app.use(bod ...

Challenge with AngularJS ng-select and ng-switch-when functionality

Struggling with implementing a selection menu on my angular charts, I encountered some challenges. The selection app template I used only displays the selection menu and graph axis on the page. Checking the console log for errors, I noticed one src URL wa ...

Tips for adjusting the status bar color in iOS for a React Native drawer

Is there a way to change the default color above the drawer navigator from white to red on iOS? I want all navigated screens to always display the color we set. https://i.sstatic.net/QszUDgmn.png import React from 'react'; import { View, Text, S ...

Click on a table cell in Vue to display its corresponding data in a modal

I have successfully implemented a modal in my Vue component that works well with static text inside it, confirming its functionality. However, when attempting to pass data from the table cell that is being clicked into the modal, I encountered an error st ...

ways to display nested arrays in angularjs

I'm having an issue with binding and displaying the value of an array. When I assign the value using the scope variable like this: $scope.StockList = obj.data Everything works fine. However, when I try to push the value into the array like this $ ...

JS is programmed to automatically redirect the user after they have clicked on a div element and a

I'm having trouble with this code that is supposed to redirect a user after they click on the div and then the next button. It's not working for me :( Here is the code I am using: $("a.xxx").click(function() { $(this).toggleClass("yyy"). ...

Controlling the display and status of DIV elements as radio button choices within a React application

I am seeking the React.js solution to a common challenge. I have five DIVs that will function as radio button options when clicked. This is what the HTML might look like: //List of option DIVs which act as radio buttons when clicked const options = () = ...

Say goodbye to my HTML5 creations

I am currently working on an HTML5 grid project that involves implementing a rectangle select tool for use within the grid. Everything is going smoothly, except for the fact that when I attempt to use the rectangular select tool, the grid disappears from t ...

What is the reason my angular plunker is not functioning as expected?

Check out this Plunker example <!DOCTYPE html> <html ng-app="app"> <head> <link data-require="qtip2@*" data-semver="2.0.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.0.0/jquery.qtip.min.css" /> <li ...

Searching with Jquery Ajax

For my search functionality, I am utilizing ajax jquery js. I found this useful code snippet here: However, I am facing some challenges with the following Javascript code: <script language="JavaScript" type="text/javascript"> <!-- function searc ...

Arranging icons at the bottom of the post with a text box that changes dynamically

My challenge is that when the content in a box overflows, the box size increases and pushes the icons out of place. I want to ensure that the icons remain in a fixed position. This is how it currently looks: The comment, delete, and likes count end up on ...