Struggling to implement a custom validation function in Angular's ngMessages.
My goal is to ensure that the total of two input values always amounts to 100.
I've crafted a new directive named totalOneHundred
, set to trigger on form changes. However, I'm stuck on accessing values of other form inputs from the link:
callback.
Sharing my code below for review. Is there a key step I'm overlooking? Any suggestions for a more efficient approach (like a sum()
function in the controller paired with ng-show
) are welcome.
Your insights are appreciated.
The form:
<!-- input box to be validated -->
<input type="number" class="form-control" name="lowBound" ng-model="ctrl.lowBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['lowBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
<!-- input box to be validated -->
<input type="number" class="form-control" name="highBound" ng-model="ctrl.highBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['highBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
The directive:
return {
restrict: "A",
require: ["^^form", "ngModel"],
link: function(scope, element, attributes, controllers) {
// Initially, form is assigned the actual form controller...
const form = controllers[0];
const model = controllers[1];
model.$validators.totalOneHundred = function (modelValue, form, element, scope) {
// Yet, the form value here shows "1".
// The modelValue represents the triggering input's value,
// but how do I tap into the other form inputs?
return true;
};
}
};