In Angular, I am trying to validate a value of a field on blur. I have a list of customers, and I want to check if the model value in the field is in my list of customers. If not, I want to set the validity to false.
I know that ng-model-options="{updateOn: 'blur'}
exists, however, I can't use this because the field is a typeahead so it must update based on the model. The validation is what needs to happen on blur.
The answer seems to be:
Write it as a function in the controller and use $setValidity just as you would in a directive. Use ng-blur to trigger the function in the input field.
-However, I keep running into examples where a custom validation (make the field invalid if the model value does not match one in the list) is only written as a directive. Are there examples of custom validation written as a function?
Write a directive that only triggers on blur.
However, I can't find examples that do either of these things. Does anybody have an example of custom validation as a function OR a directive that only updates on blur of the field?
I found this link very helpful for custom validation but I still have the same problem with the difference between a function and a directive: How to add custom validation to an AngularJS form?
As something we've been working on recently:
<form name='vm.formName' id='vm.formName' novalidate>
<input type='text' id='textField' name='textField' ng-blur='vm.blurMethod()' ng-model='vm.model.text' />
// The submit is only here for show;
<input type='submit' id='submit' ng-click='vm.submitForm()' />
</form>
In the controller:
blurMethod() {
if (this.formName.textField.$viewValue !== myArbitraryValue) {
// $setValidity called on the form, setting the textfield's validity to false
// then you can have your own validators show the error in the template
this.formName.$setValidity('textField', false);
}
}
That's off the top of my head, will take a look in the morning to see if it mirrors what we've been using. Updated the $setValidity call now.
This assumes you're using the controllerAs: 'vm' syntax, which is why the form has a name 'vm.formname' and the controller is using 'this'.