hh54188
hh54188

Reputation: 15646

Angular form validation can't show multiple error message at the same time

Here is my <input> tag need to be validated:

<input ng-minlength="0" name="name" ng-maxlength="10" ng-model="name" required/>

And I ready two error message:

<small ng-show="userForm.name.$error.minlength">Too short</small>
<small ng-show="userForm.name.$error.required">Required</small>

But when the <input> is empty, only the required error message showed, this situation also match the min-length error situation, how can I let the two error message both show?

Upvotes: 1

Views: 1908

Answers (3)

Navaneet
Navaneet

Reputation: 1387

You have used minlength as 0 and also used required attribute. So minimum length of 1 is necessary as commented by @Tj Gienger .

Without the ngRequired parameter minlength parameter means that if the user has entered a value it must be at least n characters long, but it's ok to leave the field empty. Also you need to set the ngRequired when you use min-length.

In this example(workaround) i have used minlength 5 and max length 10.

<input ng-minlength="5" name="name" ng-maxlength="10" ng-model="myname" ng-required="true"/>
<div ng-show="userForm.name.$error.minlength">Too short</div>                    
<div ng-show="userForm.name.$error.required">Required</div>
<div ng-show="userForm.name.$error.required">Too short</div>

Upvotes: 1

Baljinder Sekhon
Baljinder Sekhon

Reputation: 1

As already mentioned by Navaneeth change your minlength to greater then 0 minlength message will only show when your criteria is not met so when the text box is empty its length would be 0 which is equal to the minlength value you have set.

Upvotes: 0

eXaminator
eXaminator

Reputation: 353

As was already stated you would need a min length on 1.

In addition to that: Most (if not all) validators in angular (except required of course) return true if the value is empty.

See here for an example: https://github.com/angular/angular.js/blob/master/src/ng/directive/validators.js#L87

So this is actually by design and there is not much you can do about this but write your own validators.

Upvotes: 0

Related Questions