JROB JROB - 1 year ago 53
jQuery Question

jQuery- How to properly test whether input field is blank? By value or length?

In doing some jQuery validation, I would like to test whether or not the form field was left blank. Which is the best/most stable way of doing this- by testing that the value is not blank or by testing the length is not zero?

if (inputValue != '') { // Do something


if (inputValue.length > 0) { // Do something

Answer Source

You've said inputValue comes from a form field, and you're using length, so we know it's a string

Your two examples are equally stable. Neither is "best" except according to personal opinion.

Also note that an empty string is falsy and a non-empty string is truthy, so you can also do

if (inputValue)

Again, not "best" or "non-best," it's up to you which of the three you prefer.

Additionally, string length cannot be negative, and 0 is falsy while all positive values are truthy, so you can do:

if (inputValue.length)

That brings us up to four. Take your pick. They all do the same thing in different ways.

Depending on your definition of "empty," you might also want to throw a trim in there:

if (inputValue.trim() != '')

// or

if (inputValue.trim().length > 0)

// or

if (inputValue.trim().length)

// or

if (inputValue.trim())