I have a form that has maybe 15-20 fields. Each one of them contains an attribute that looks something like this:
ng-class='addressForm.city.$invalid && addressForm.city.$touched ? "error" : ""'
So I have that long string of code repeated 15-20 times. This sets my DRY alarm bells off bigtime.
I could devise my own way to make this more DRY but I don't want to re-invent the wheel. Is there a gererally-accepted way of keeping Angular form validation DRY?
As @lain said, you don't have to add another class (like
error
) if the field is invalid, Angular adds that for you by default, it's just the name that differs (ng-invalid
). You can see how is that used here (the official form example from Angular).If you still want to do this in your way, this is the implementation of my latest comment, using
ngChange
directive.The html:
The change event:
This is not good practice (to manipulate the DOM in the controller), you should implement that in a directive, but binding a directive to each field would add watchers and I, personally, try to avoid as much as possible using too many watchers.
A more elegant option would be to combine this
ngChange
withngClass
or simply go with that simple DOM manipulation within controller. It's your choise :)