Set form as invalid in angularjs

I need to set ng-form as invalid at the beginning, as this is a later part of the wizard. The form contains a grid with elements. Each element has its own validation, but the problem is that when there are no elements, the form shows as valid. I need to mark this as unacceptable for the start case, when the number of rows is 0. How can this be done?

+8
angularjs
Jan 14 '14 at 10:43
source share
2 answers

After some research, the following code works fine for me. In the controller:

//Set the form as invalid for start. $timeout(function(){ $scope.orderForm.productsForm.$invalid = true; }); 

A timeout ensures that we get access to the form. They are not built on the first pass through the controller, so a timeout or clock is needed. Then we mark the form as invalid. A better way would be to search for input, which we can mark as invalid using the documented api $setValidity on ngModelController, but in my case there is no input yet, so we do it in a dirty way.

One caveat is that when you install it directly as above, the corresponding $ invalid ===! The $ valid invariant is broken, so be careful with this hack.

+18
Jan 14 '14 at 10:51
source share

I think the next solution is cleaner.

 $scope.$watch('myForm', function (a, b) { $scope.myForm.$setValidity('custom', false, window); // 'custom' validation key, binds window as form control }); 

I like $watch better; Initially, I was going to check "if the form was created yet", and only after that establish the correctness.

But it seems that this is really not necessary, the form is created before $ watch is executed its initial time (so that the clock does not cause any changes).

$setValidity seems to be part of the ngForm API (I found the source code in form.js ), and it is used by the form controls themselves, which set $ valid and $ to be invalid.

+1
Feb 08 '17 at 22:18
source share



All Articles