[angularjs] How do I check form validity with angularjs?

I'm very new to angularjs. Say my app has a form. Using the inspector, I noticed that if angularjs thinks that the form is invalid, it adds an ng-invalid class to the form. Lovely.

So it seems that in order to check if the form is valid I need to pollute my code with Jquery selector?! What is the angularjs way to indicate form validity without using a form controller?

This question is related to angularjs

The answer is

When you put <form> tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form> will satisfy:

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

So to check form validity, you can check value of $scope.yourformname.$valid property of scope.

More information you can get at Developer's Guide section about forms.


<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>

  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {

You can also use myform.$invalid




  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.


angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';


<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}

Source: AngularJS: API: form

Questions with angularjs tag:

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443 Disable Chrome strict MIME type checking Consider marking event handler as 'passive' to make the page more responsive Angular get object from array by Id SyntaxError: Unexpected token o in JSON at position 1 Failed to load resource 404 (Not Found) - file location error? Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS Usage of $broadcast(), $emit() And $on() in AngularJS How to return data from promise Send FormData with other field in AngularJS check null,empty or undefined angularjs How to run html file using node js how to find array size in angularjs How to filter array when object key value is in array How do I fix the npm UNMET PEER DEPENDENCY warning? Send multipart/form-data files with angular using $http Display number always with 2 decimal places in <input> Angular pass callback function to child component as @Input similar to AngularJS way ng-if check if array is empty Firebase TIMESTAMP to date and Time What is the Angular equivalent to an AngularJS $watch? Generate PDF from HTML using pdfMake in Angularjs AngularJS POST Fails: Response for preflight has invalid HTTP status code 404 Why and when to use angular.copy? (Deep Copy) How to make use of ng-if , ng-else in angularJS Check if value exists in the array (AngularJS) How to check for an empty object in an AngularJS view TypeError: window.initMap is not a function CORS with spring-boot and angularjs not working File Upload with Angular Material AngularJS $watch window resize inside directive Unexpected token < in first line of HTML Module is not available, misspelled or forgot to load (but I didn't) Assign value from successful promise resolve to external variable How to send POST in angularjs with multiple params? ng if with angular for string contains Should I use typescript? or I can just use ES6? How do I trim() a string in angularjs? How to push object into an array using AngularJS Adding class to element using Angular JS