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

Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

You can loop through form.$error.pattern.

$scope.updateProfile = function() {
    var error = $scope.profileForm.$error;
    angular.forEach(error.pattern, function(field){
        if(field.$invalid){
            var fieldName = field.$name;
            ....
        }
    });
}

Solution 5:

I wanted to display all the errors in the disabled Save button tooltip, so the user will know why is disable instead of scrolling up and down the long form.

Note: remember to add name property to the fields in your form

    if (frm) {
        disable = frm.$invalid;
        if (frm.$invalid && frm.$error && frm.$error.required) {
            frm.$error.required.forEach(function (error) {
                disableArray.push(error.$name + ' is required'); 
            });
        }
    }
    if (disableArray.length > 0) {
        vm.disableMessage = disableArray.toString();
    }