1

I'm trying to output invalid field names in a generic way. The below does this by looping through all the fields in the form and just appending to a string with the key name. It gets run when you click a submit button:

for (var key in form) {
    if (key.indexOf("$") !== 0) {
        if (form[key].$invalid) {
            str += '- ' + key + '<br />';
        }
    }
}

My only issue with this is the order that the keys appear dont match the order that the fields appear on the page. I'm assuming it's related to how the fields themselves are created, since dynamically generated fields seem to appear before normal fields. I'd really like to maintain the order, but can't think of a good way to do this.

Was hoping someone would have a suggestion?

2 Answers 2

4
+50

You can simply iterate over your controls by going through the DOM:

// Assuming $element is your <form>
var invalidFields = [];
$element.find('.ng-invalid').each(function() {
    invalidFields.push(this.name);
});

This approach is just using the fact that NgModelController will set ng-invalid CSS class on all invalid controls. Using Angular does not mean you are forbidden to work with DOM.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the approach that I ended up using, to solve the issue that brought me to this question originally. I am not sure that it is the answer that the original asker was looking for. If no better answer is given before the bounty expires, I will award it too you.
0

have a array with the fields name in order and iterate over it to check

for ex: 
var fieldsInOrder = ["field1", "field2", "field3"];//can creaate in dynamically by iterating Dom also or have a static one.
for (var i=0; i<fieldsInOrder.length; i++) {
    var currentField = fieldsInOrder[i];
    if (form[currentField ].$invalid) {
        str += '- ' + key + '<br />';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.