Mpondomise Mpondomise - 26 days ago 14
AngularJS Question

angularjs error message even without touching the field

why the following angularjs form throws in the following errors whereas, nothing is typed in the input field, nor clicked on it.


It is throwing in "It's a valid name!" and Error in the field. at the same time, even without typing or clicking on the field.
Does anyone know the reason?



<div class="form-group" ng-class="{'has-error':Form.field1.$dirty && Form.field1.$invalid, 'has-success':Form.field1.$valid}" >
<label class="control-label" >
Name
</label>
<input class="form-control" ng-model="myModel.field1" ng-minlength="3" ng-maxlength="20"
style="" type="text" name="field1" placeholder="Enter the name"/>
<p class="error text-small block" ng-show="Form.field1.$error.maxlength">Too long!</p>
<p class="error text-small block" ng-show="Form.field1.$error.minlength">Too short!</p>
<p class="error text-small block" ng-show="Form.field1.$dirty && Form.field1.$error">Error in the field.</p>
<p class="success text-small" ng-show="Form.field1.$valid">It's a valid name!</p>
</div>

Answer

The reason is because having a length of 0 is valid for 'ng-minlength'.
If you want 0 to be invalid, you must use 'ng-required'.

My guess is that you want something like the following:

<div class="form-group" ng-class="{'has-error':Form.field1.$dirty && Form.field1.$invalid, 'has-success':Form.field1.$valid}">
    <label class="control-label" >
        Name
    </label>
    <input class="form-control" ng-model="myModel.field1" ng-minlength="3" ng-maxlength="20" ng-required="true"
           style="" type="text" name="field1" placeholder="Enter the name"/>
    <p class="error text-small block" ng-show="Form.field1.$dirty && Form.field1.$error.maxlength">Too long!</p>
    <p class="error text-small block" ng-show="Form.field1.$dirty && Form.field1.$error.minlength">Too short!</p>
    <p class="error text-small block" ng-show="Form.field1.$dirty && Form.field1.$error.required">Required!</p>
    <p class="error text-small block" ng-show="Form.field1.$dirty && (Form.field1.$error.maxlength || Form.field1.$error.minlength || Form.field1.$error.required)">Error in the field.</p>
    <p class="success text-small" ng-show="Form.field1.$valid">It's a valid name!</p>
</div>
Comments