Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Is there any way to determine which fields are making a form invalid?

I have the following code in an AngularJS application, inside of a controller, which is called from an ng-submit function, which belongs to a form with name profileForm:

$scope.updateProfile = function() {
  if($scope.profileForm.$invalid) { 
    //error handling..
  }
  //etc.
};

Inside of this function, is there any way to figure out which fields are causing the entire form to be called invalid?

like image 233
GSto Avatar asked Aug 16 '13 20:08

GSto


People also ask

How do you check whether a form is valid or not in AngularJS?

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.

What is $valid in AngularJS?

AngularJS offers client-side form validation. AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state. AngularJS also holds information about whether they have been touched, or modified, or not.

What is $dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.


3 Answers

Each input name's validation information is exposed as property in form's name in scope.

HTML

<form name="someForm" action="/">
    <input name="username" required />
    <input name="password" type="password" required />
</form>

JS

$scope.someForm.username.$valid
// > false
$scope.someForm.password.$error
// > { required: true }

The exposed properties are $pristine, $dirty, $valid, $invalid, $error.

If you want to iterate over the errors for some reason:

$scope.someForm.$error
// > { required: [{$name: "username", $error: true /*...*/},
//                {$name: "password", /*..*/}] }

Each rule in error will be exposed in $error.

Here is a plunkr to play with http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview

like image 110
Umur Kontacı Avatar answered Oct 18 '22 02:10

Umur Kontacı


For checking which field of form is invalid

console.log($scope.FORM_NAME.$error.required);

this will output the array of invalid fields of the form

like image 28
Shivek Parmar Avatar answered Oct 18 '22 03:10

Shivek Parmar


If you want to see which fields are messing up with your validation and you have jQuery to help you, just search for the "ng-invalid" class on the javascript console.

$('.ng-invalid');

It will list all DOM elements which failed validation for any reason.

like image 15
Thassae Santos Avatar answered Oct 18 '22 03:10

Thassae Santos