Check if a input box is empty

vivek picture vivek · May 22, 2013 · Viewed 171k times · Source

How can I check if a given input control is empty? I know there is $pristine property on the field which tells that if a given field is empty initially but what if when someone fill the field and yanks the whole content again?

I think above feature is necessary as its important for telling the user that field is required.

Any idea will be appreciated!

Answer

Supr picture Supr · May 22, 2013

Quite simple:

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

You could also use ng-hide="somefield.length" instead of ng-show="!somefield.length" if that reads more naturally for you.


A better alternative might be to really take advantage of the form abilities of Angular:

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Updated Plnkr here.