Reputation: 1030
I've created a small angularjs directive for displaing validation error on my page
Here is code
.directive('validationErrors', function() {
return {
templateUrl: '/Content/biz/templates/common/validation-errors.html',
replace: true,
restrict: 'E',
scope: {
modelToValidate: '=',
modelMinLength: '=',
modelMaxLength: '=',
modelPattern: '='
}
}
});
And template for it
<div class="col-sm-5 pull-right" data-ng-show="modelToValidate.$dirty && modelToValidate.$invalid">
<span class="label label-warning" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be {{modelMinLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be {{modelMaxLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.pattern">Model should have {{modelPattern}}</span>
Than I bind it to a model
<div class="col-sm-4">
<input class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/>
This generates markup like so
<div class="col-sm-4">
<input class="form-control ng-valid-maxlength ng-dirty ng-valid-parse ng-invalid ng-invalid-required ng-touched" ng-model="data.Main.FullName" ng-maxlength="1000" required="">
<div class="col-sm-5 pull-right ng-isolate-scope" model-to-validate="data.Main.FullName" model-max-length="1000">
<span class="label label-warning ng-hide" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be </span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be 1000</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.pattern">Model should have </span>
But If binded model has error nothing is showen. Please help me to understand why is it so.
Upvotes: 0
Views: 154
Reputation: 42669
I think what you need to pass to you form is a a ngModelController
instance, whereas what you are passing is a model instance.
Firstly change the input to have a name attribute
<input name="fullName" class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/>
(Also make sure your form has a name attribute, let's assume it is myForm
)
And then the directive parameter should be
<div model-to-validate="myForm.FullName" model-max-length="1000">
This should now work. Remember all the properties that you are using like $error
are defined on the NgModelController instance not on the model.
Also what you are doing can be done in Angular 1.4 using ngMessage
Upvotes: 1