VictorySaber VictorySaber - 1 month ago 14x
AngularJS Question

Angular - $viewValue or $modelValue in validation?

I'm new to Angular and I want to check I am doing form validation right. I want to display an appropriate message when the user has entered more than 100 characters in an input field.
For this I am using $viewValue. Would $modelValue be better for validation since it is what has been 'saved' in the controller? Is there a better way to do this kind of specific validation?

<div class="form-group">
<label for="Forename" class="control-label col-md-2">Forename</label>
<div class="col-md-10">
<input id="forename" type="text" class="form-control"
ng-model="vm.customer.Forename" />

<li ng-show="detailsForm.detailsForename.$error.required">
Forename must be filled in
<li ng-show="!detailsForm.detailsForename.$valid">
Forename was not valid
<li ng-show="detailsForm.detailsForename.$viewValue.length > 100">
Forename must be no more than 100 characters

UPDATE: I had tried vm.person.Forename but for whatever reason it was not working. If it should work I shall revisit that as a possibility.
Using $valid is not enough because if the input field is empty I will get the error message for Required, and for > 100 (because $valid=false)


As noted in the ngMaxlength docs: "The validator sets the maxlength error key if the ngModel.$viewValue is longer than the integer ..."

So in your case that would be: detailsForm.detailsForename.$error.maxlength

You should never need to access an ngModel's $viewValue or $modelValue from the template.