Validating empty input with jQuery

I post comments via $ .ajax. However, I want to check that some content has been entered in the input field. At the moment I am using this:

if ($("#comments").val().length != 0){ 

However, this only works if the user leaves the input space, if you leave a space or return, then it will pass. How can I improve this if?

+7
jquery
source share
4 answers

Delete the space before checking for empty:

 if ($("#comments").val().replace(/^\s+|\s+$/g, "").length != 0){ 
+11
source share

you can go for the trim function ... google give us good links. btw ... jQuery has trim-function

eg.

 var trimmedValue = jQuery.trim($('#comments').val()); if (trimmedValue.length > 0) { // TODO } 
+8
source share

In javascript

 //Following all return true "" == false " " == false " " == false " " == false //Not related to question but interesting //Following all (also) return true !" " == false !" " == false !" " == false //Except !"" == false //returns false 

(verified using the Firebug console and the Chromium Developer Tools console).

+1
source share

I know this is an incredibly late answer, but I use this ...

 var self = $(this).val(); if (!self || self[0] == ' '){ //////do something } 

and it works well! hope someone else can benefit from it!

+1
source share

All Articles