I have several fields in the form:
<input name="participant{{$index}}email" type="email" ng-model="participant.email" ng-trim="true"
required ng-minlength="1" ng-maxlength="255"
email-uniqueness-validator="{{$index}}">
I use the emailUniquenessValidator directive to check if any participant entered the same email. If so I display error message:
<div ng-messages="enroll['participant' + $index + 'email'].$error">
<div ng-message="emailUniqueness">The email addresses must be different for every applicant...</div>
</div>
The problem is when I have two fields with the same email and both of them show error. Then user edits one email so it's different than any other email and the error message on the field disappears as expected, but how can I remove the error message from the second email field that became unique by editing the first email field?
The directive:
.directive('emailUniquenessValidator',
function() {
return {
require : 'ngModel',
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function () {
var currentEmailFieldNo = attrs.emailUniquenessValidator;
var diffEmails = differentEmails(scope, currentEmailFieldNo);
ngModel.$setValidity('emailUniqueness', diffEmails);
if (!diffEmails) {//one field has changed and there is no duplicates, but we need to remove validation errors from the other field
cleanDuplicateEmailErrors(scope);
}
});
}
}
});
differentEmails function:
function differentEmails(scope, currentEmailFieldNo) {
differentEmails = true;
var currentEmail = currentEmailFieldNo >= 0
? scope.applicantEnrollDto.participants[currentEmailFieldNo].email
: scope.applicantEnrollDto.email;
var mainEmail = scope.applicantEnrollDto.email;
if (currentEmailFieldNo < 0) {
if (emailInArray(currentEmail, scope.applicantEnrollDto.participants)) {
differentEmails = false;
}
} else {
var applicantsNo = scope.applicantEnrollDto.participants.length
var differentEmails = true;
if (applicantsNo) {
differentEmails = !hasDuplicates(scope.applicantEnrollDto.participants);
if (differentEmails) {
if (currentEmail === mainEmail) {
differentEmails = false;
}
}
}
}
return differentEmails;
}
The problem was solved easily by accessing form in the scope
$scope.form["participant"+i+"email"].$setValidity('emailUniqueness', errorsOff);