When it comes to basic validation directives like ng-minlength
, they prevent ngModel from updating until the validation criteria are met. While this behavior is intentional and beneficial in many scenarios, there are cases where it may not be ideal.
To work around this issue while still leveraging ngModel-based validation (including form validity), you can manually define the validation step using $setValidity
. This involves removing the ng-minlength
attribute and implementing an ng-change
callback instead.
Additionally, ensure that your form element has a name and is part of a named form so that you can access the relevant ngModelController.
<form name="formCtrl">
<textarea ng-trim="false"
ng-model="form.text"
ng-change="checkTextLength()"
name="formText">
</textarea>
<p>{{240 - form.text.length}} left</p>
</form>
In your controller (assuming you are using only $scope
):
$scope.checkTextLength = function(){
if($scope.form.text.length < 20){
$scope.formCtrl.formText.$setValidity('minlength', false);
} else{
$scope.formCtrl.formText.$setValidity('minlength', true);
}
if($scope.form.text.length > 240){
$scope.formCtrl.formText.$setValidity('maxlength', false);
} else{
$scope.formCtrl.formText.$setValidity('maxlength', true);
}
}
I have created a functional example based on your codepen in this link: here. I also added a section in the template to display the validity state.