Reputation: 3547
The ng-required attribute is helpful to make a field required based on a condition:
<input ... ng-required="object.isRequired" \>
But how can this type of use be extended into using my own custom validation directives? For example, say I have a custom validation fieldsMatch. Now I want to add this validation to the input field based on the property "object.needsToMatch". I would hope there would be something like:
<input ... fieldsMatch="object.needsToMatch"
If the solution is to create another directive that would handle the condition, then how can I replace it inline (inside the input element)?
Secondary question: Then how to get this working when the custom validation takes an attribute, such as in the case of fieldsMatch validator, the model's field that this field needs to match with.
Upvotes: 0
Views: 548
Reputation: 9351
I would create a directive to handle this that is restricted to an attribute.
<input ... ng-model="inputModel" fieldMatchValidator fieldToMatch="object.needsToMatch" />
and in the directive:
...directive('field-match-validator', function(){
require: 'ngModel',
scope:{
fieldToMatch: '='
},
link: function(scope, element, attrs, ngModelCtrl){
//watch on the model and validate it against scope.fieldToMatch
}
});
Obviously this is somewhat crude, but should get you started.
Upvotes: 1