In my project, I have implemented a directive that performs input validation within a form based on the values of their properties such as $valid and $untouched. The directive checks for validation when the input is "touched" and changes the font and border colors to red or green accordingly. However, if the input remains "untouched", no action is taken.
Due to using ngBootBox's custom dialog, I do not have a submit type button in my form. Instead, I rely on the callback function of the "Create" button to handle data passing and saving.
An issue arises when I click the "create" button and some fields are left empty, causing the form to be considered invalid. Since the inputs remain untouched, the $watch function does not get triggered. Is there a way to force all child inputs of the form to be marked as touched with something like $scope.createProjectForm.$setTouched(true)?
I attempted another approach by iterating through the inputs and setting them as touched, but it did not yield the desired result:
angular.forEach($scope.createProjectForm, function(field){
field.$setTouched(true);
});
Below is the code for my validation directive:
angular.module('mean.theme').directive("inputValidation", function () {
return {
restrict: 'EA',
require: 'ngModel',
link: function (scope, inputElement, attrs, ngModelCtrl) {
// Validation logic here
}
};
});
This snippet shows part of my controller code where the create function is defined:
$scope.create = function () {
// Dialog options and logic here
};
Lastly, this portion presents the structure of my form in HTML:
<form role="form" name="createProjectForm">
<!-- Form inputs here -->
</form>
- EDIT:
After further exploration, I discovered a simpler method to achieve the desired behavior:
You can manually set:
$scope.createProjectForm.$setSubmitted()
to true
Then, you can implement a $watch function on the children (inputs) to monitor this change:
scope.$watchGroup([
function(){
return ngModelCtrl.$untouched;
},
function(){
return ngModelCtrl.$valid;
},
function(){
return ngModelCtrl.$$parentForm.$submitted;
}
], function(Paramaters){
// Code implementation here
}