Validating forms in angular: How to check if a form is legitimate

I am attempting to validate a form using Angular to determine its validity.

The form structure is as follows:

<form name="form" novalidate>
    <p>
        <label>Number: </label>
    <input type="number" min="0" max="10" ng-model="test.number" required />
    </p>
    <p>
        <label>Name: </label>
    <input type="text" ng-model="test.name" required />
    </p>
    <button ng-click="sendTest(test)">Submit</button>
</form>

Within the sendTest function, I have the following code:

angular.module('demo', [
      ]).controller('MainCtrl', function($scope){
        $scope.test = {
          name: 'das'
        };

        $scope.sendTest = function(test) {
          console.log(form.$valid);
          console.log(test.$valid);
        }
      });

The issue arises when both form.$valid and test.$valid return as undefined. I have tried to troubleshoot using the following resources:

http://www.youtube.com/watch?v=J82OD76QhPo

To view the complete code for this demo, please visit: http://plnkr.co/edit/l0E62KPJu4Z2r15VNjJq

Answer №1

form is now included in the scope, so you can check its validity using: console.log($scope.form.$valid)

Just a side note, the name form was chosen based on the value specified in the form tag's name attribute. You can also assign name attributes to individual input fields if you want to track their state from the controller.

Here's an example for reference: http://plnkr.co/edit/Ra98yIFYso94flDIqNCD?p=preview

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 functionality to open the menu by clicking is experiencing issues

I'm attempting to replicate the Apple website layout. HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" conte ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

AngularJS/Bootstrap: Tips for keeping accordion-heading at the top during scrolling

I am working with a directive that contains an angularjs accordion list. Each section in the accordion-body has lengthy content. The issue I am facing is that when I expand an item and scroll down to view all the content, the header of the item goes out of ...

The Hidden Div containing NicEdit is now shrunk down to a smaller size

Attempting to integrate the NicEdit editor for a hidden textarea stored within a div has presented some challenges. The goal is for the targeted textarea's parent div to be revealed upon the user clicking a button, with the textarea's width set t ...

ReactJS: Unable to navigate to a new page when moving from a page with automatic refresh

Every 5 seconds, I automatically refresh a page (Page1) using setTimeout and a callback function. However, every time I navigate to a new page (Page2), it quickly redirects back to Page1 after a few moments. I have tried using window beforeunload event l ...

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Utilizing a custom function to filter Firestore collection data based on location proximity

I have a question about filtering a Firestore collection using a function where the values of the documents in the collection are used as arguments. Let's say we have a Firestore collection with documents structured like this: { pointOfInterest: "S ...

What is the solution to rectifying the issue with graphql codegen?

Upon running the command "yarn graphql-codegen," an error occurred and I am unsure how to resolve it: % yarn graphql-codegen yarn run v1.22.4 warning package.json: No license field $ /Users/xxx/node_modules/.bin/graphql-codegen ✔ Parse Configuration ⚠ ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

Generating an array of quarter numbers and year based on the current date in Node.js using Moment.js - a simple guide

I need to generate an array of quarter numbers and year numbers based on the current timestamp in Node.js. For instance, if the current quarter is Q1 and the year is 2020, I want to create an array similar to the one below. quarters = ['Q2-2019' ...

Processing .dat files using JavaScript

Currently, I am attempting to utilize JavaScript to upload a file named example.dat. Initially, I believed that the correct approach would be using fileReader; however, it appears that this method is unable to process this specific format. The objective i ...

Protractor Identifier Element Class Manifestation

Currently, I am exploring different options to replace the usage of by.xpath('//*[contains(@class,"favorites-button-icon")]') in Protractor. Unfortunately, I haven't been able to identify a specific identifier that allows matching by 'c ...

Determining whether the user has a token stored in the localStorage is a crucial step in my

I have an app that calls a Login API and returns a token. I store the token in localStorage, but I'm unsure how to validate if the user has a token to log in. What steps can I take to solve this? Below is my login page where I store the token in loca ...

Navigating through AngularJS routes triggers Ajax data retrieval upon changing routes

I'm struggling to grasp the Angular approach for the following scenario... I have a router set up, and when the route changes and the templateUrl is provided, I want to initiate an Ajax call to retrieve some JSON data. I don't want to wait for ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

Troubleshooting: AngularJS View Fails to Update with Defer and Factory

I've encountered an issue where my view doesn't update when I create a new setting without refreshing the page. Can someone provide guidance on how to resolve this issue? If there's a better approach to achieving this, please share that as w ...

Importing the .css file within a React component for dynamic styling

In my component, I am trying to dynamically load a .css file based on the result of an AJAX call in componentDidMount(). I have attempted adding a <link> element in the render return (which did not work), and also tried injecting the tag directly int ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...