I've got an AngularJS form that has a custom validator to check with the server backend whether the input value is unique or not. The unique validation is done by the mob-async-validate-unique
directive in the example below.
The form looks somewhat like this:
<form class="form-floating" novalidate="novalidate" ng-submit="saveItem(item)">
<div class="form-group filled">
<label class="control-label">Key</label>
<input type="text" class="form-control" ng-model="item.Key" mob-async-validate-unique >
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg btn-primary">Save</button>
</div>
</form>
I want to use the same form for both adding as well as editing the model that I put on $scope
.
Everything works great except for the fact that the unique validator fires on the edit operation even when the value is the same as the original value and then validates unique as false because the value already exists. The validator marks the field invalid in both the following cases:
- Change the field value and then edit it back to the original value
- Submit the form without changing anything
What is the best way to achieve this? The naive way I can think of is that I'll have to store the original value on a $scope.originalValue
variable, and then add an attribute on the unique validated element to name this variable. Within the validator I'll read this value from the $scope and compare it with the current value to make the validator accept it when the two values are the same. I'm going ahead and implementing this.
I use the unique validator in a generic way in several places (yes, there are several more attributes in use on the <input>
element that I've not included in the code sample, for simplicity and legibility) and need the validator to function completely on it's own and ideally want to keep the controller $scope
out of the picture so that I can use the custom async validator anyway / anywhere I want.