I would like some feedback on improving/designing custom form validations(multiple fields) the Angular way.
I have some form input fields that are generated by ngRepeat. Basically, the next input must be greater than the the previous. I called these fields beginLevel.
My current implementation is as follow: I am using ngBlur to call a controller function. This function loops through my model comparing the index[i].beginsAtLevel with index[i-1].beginsAtLevel. In the event that the current beginsAtLevel is less than that the previous beginsAtLevel I grab the id of the form-group e.g.
previousIndex = angular.element(document.querySelector('#beginsAtLevel' + (i - 1))); and
currentIndex = angular.element(document.querySelector('#beginsAtLevel' + i));.
I subsequently, add the has-error class to the input fields.
previousIndex.addClass('has-error'); currentIndex.addClass('has-error');
I also have another function removeErrors(), which loops through my model and removes the has-error class.
This approach works but I feel its a bit of a hack. How could I implement/improve this using a directive? I have seen plenty of examples online that validate only one input at a time.
Here is my function for reference:
function validateTiersBeginLevel(tiers) {
var previous, current, previousIndex, currentIndex;
for (var i = 1; i < tiers.length; i++) {
previous = tiers[i - 1].beginsAtLevel;
current = tiers[i].beginsAtLevel;
if (Number(current) <= Number(previous)) {
previousIndex =
angular.element(document.querySelector('#beginsAtLevel' + (i - 1)));
currentIndex =
angular.element(document.querySelector('#beginsAtLevel' + i));
previousIndex.addClass('has-error');
currentIndex.addClass('has-error');
} else {
clearErrors(tiers);
}
}
}
as well as my input field(s) generated by ngRepeat:
<div class="form-group"
ng-class="{'has-error': tierForm.beginsAtLevel{{$index}}.$touched &&
tierForm.beginsAtLevel{{$index}}.$invalid}"
id="beginsAtLevel{{$index}}">
<p class="col-md-4 col-xs-4">Begin Level</p>
<div class="col-md-8 col-xs-8">
<input type="text"
class="form-control"
name="beginsAtLevel{{$index}}"
ng-model="tier.beginsAtLevel"
ng-blur="rp.validateTiersBeginLevel(tiers);"
required>
<div class="text-danger"
ng-messages="tierForm['beginsAtLevel'+ $index].$error"
ng-if="tierForm['beginsAtLevel'+ $index].$touched">
<span ng-message="required">Begin Level is required</span>
</div>
</div>
</div>
