Reputation: 1115
Why do I get the success message even without entering something or even without touching the field?
<div class="form-group"
ng-class="{'has-error':Form.description.$invalid, 'has-success':Form.description.$valid}">
<label class="control-label" translate="dashboard.field1"></label>
<input class="form-control" ng-model="model.field1"
ng-minlength=3 ng-maxlength=20
type="text" name="description"
placeholder="Enter your text"/>
<span class="error text-small block"
ng-if="Form.description.$error.maxlength">Too long!</span>
<span class="error text-small block"
ng-if="Form.description.$error.minlength">Too short!</span>
<span class="success text-small" ng-if="Form.description.$valid"> Success!</span>
</div>
this form field is not required
as you see in my input parameters. I just want to control the input text with min and max, if ever the user wants to put in text so that it meets these requirements; but the field itself should not be required, because when I submit the form, I don't want it to prevent the user from submitting it just because one field was left out.
Upvotes: 0
Views: 45
Reputation: 776
Its because the empty is valid, even with the min length. If empty is not valid you should add the required
attribute.
Or, you can add the $dirty
on the ng-if. Now it only shows success if the user type something. But, if the user erase the input text the description is still "dirty".
Or, as I suspect is what you need, change the ng-if="Form.description.$valid && model.field1"
. Now the Success will show only if is valid (3 - 20) and is not empty.
<form name="Form">
<div class="form-group" ng-class="{'has-error':Form.description.$invalid, 'has-success':Form.description.$valid}">
<label class="control-label" translate="dashboard.field1"></label>
<input class="form-control" ng-model="model.field1" ng-minlength=3 ng-maxlength=20 type="text" name="description" placeholder="Enter your text" />
<span class="error text-small block" ng-if="Form.description.$error.maxlength">
Too long!
</span>
<span class="error text-small block" ng-if="Form.description.$error.minlength">
Too short!
</span>
<span class="success text-small"
ng-if="Form.description.$valid && model.field1"> Success!</span>
</div>
Upvotes: 1
Reputation: 1365
This happens because when your angular bootstraps the form in turn will be replaced with error attributes to elements.To avoid this pitfall for the first time,Use
$dirty:Checks if the element is made dirty
<span class="error text-small block" ng-if="Form.description.$dirty && Form.description.$error.maxlength">
Too long!
</span>
Upvotes: 0