CodexBloom - Programming Q&A Platform

AngularJS 1.8: Problems with dynamic form validation not triggering on model changes

๐Ÿ‘€ Views: 827 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
angularjs validation custom-directive JavaScript

I'm following best practices but I'm building a feature where I'm experiencing an scenario with dynamic form validation in AngularJS 1.8... I have a form that contains several inputs, and I want to validate them based on the user's input dynamically. I've set up a custom directive to handle the validation logic, but it seems that the validation doesn't trigger when the model changes. Here's the relevant part of my code: ```javascript angular.module('myApp', []) .controller('MyController', function($scope) { $scope.user = { email: '', password: '' }; }) .directive('validateEmail', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$validators.email = function(modelValue, viewValue) { const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailPattern.test(modelValue); }; scope.$watch('user.email', function(newValue) { ngModel.$validate(); }); } }; }); ``` In my HTML, I have: ```html <form name="userForm" novalidate> <input type="email" name="email" ng-model="user.email" validate-email required /> <div ng-show="userForm.email.$behavior.email">Invalid email address.</div> </form> ``` I've tried using `$watch` to observe changes to the `user.email` model, but it doesnโ€™t seem to trigger the validation as expected. I also checked that the directive is correctly applied to the input field. However, the validation message isnโ€™t showing up when I enter an invalid email. Iโ€™ve verified that the `$validate` method is being called, but the `$behavior.email` object does not seem to reflect the validation state. I also get no console errors, which makes it harder to debug. Has anyone faced a similar scenario? Any insights on why the validation might not be updating dynamically would be greatly appreciated! Has anyone else encountered this? I'm working in a macOS environment. Any advice would be much appreciated.