CodexBloom - Programming Q&A Platform

AngularJS 1.8: Problems with dynamic form validation and $validators in custom directives

πŸ‘€ Views: 3 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
angularjs validators directives JavaScript

I'm integrating two systems and I'm stuck trying to I'm wondering if anyone has experience with I've been banging my head against this for hours..... I'm currently working on an AngularJS 1.8 application where I need to create a custom form directive that includes dynamic validation rules based on user input. The directive should allow for conditional validation, but I am working with issues with the `$validators` not being triggered as expected. Here’s a simplified version of what I've implemented so far: ```javascript app.directive('dynamicForm', function() { return { restrict: 'E', require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$validators.conditionValidator = function(modelValue, viewValue) { var value = modelValue || viewValue; return value.length > 5; }; scope.$watch('someCondition', function(newVal) { ngModel.$validate(); }); } }; }); ``` The scenario arises when I change `someCondition`, which should theoretically trigger the `$validate()` method, but the behavior message associated with `conditionValidator` does not appear, and the form remains valid regardless of the input length. The `$validators` don't seem to be firing at all after the initial validation. I have also tried using `ngModel.$setValidity` manually to update the state, but no luck. I verified that `someCondition` changes correctly by logging its value. Are there specific best practices for implementing dynamic validators in custom directives that I might be overlooking? Could this be a timing scenario with how AngularJS processes $watchers and validations? Any insights would be appreciated! What am I doing wrong? What are your experiences with this? The stack includes Javascript and several other technologies. Thanks for your help in advance! I appreciate any insights! Any advice would be much appreciated.