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!
You can use the isspace() and "" (empty string).
To check if an input is empty in React:Call the trim() method on the field's value. Access the length property on the value. If the field's value has a length of 0 , then it is empty, otherwise it isn't.
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.
Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false
So you could write:
<input ng-model="somefield"> <span ng-show="!somefield">Sorry, the field is empty!</span> <span ng-hide="!somefield">Thanks. Successfully validated!</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With