-2

how do i validate if my text box has only spaces in it? I've validated for an empty text box, but how do I validate for a text box with only spaces.

I want the text box to behave similar to an empty text box if the entered string is only spaces.

Thanks.

ikartik90
  • 2,695
  • 6
  • 26
  • 38
Christian Eric Paran
  • 980
  • 6
  • 27
  • 49
  • 2
    **Such a lazy question** .... include some of your current code ... include some examples of input and expected result ... and do you want this in PHP or in JavaScript ? – Manse Mar 13 '12 at 12:05
  • [Trim](http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript) the value before checking it's contents. – Aaron W. Mar 13 '12 at 12:06

4 Answers4

1

If I'm understanding your question correctly, you're looking for something like this:

function consistsEntirelyOfWhitespace(textBox) {
    return (textBox.value.match(/^\s+$/) !== null);
}
pete
  • 24,141
  • 4
  • 37
  • 51
0

Always trim the value of your text fields, that way you never have to validate on SPACE, example (using jQuery):

var value = $.trim(('#theId').val());
Loolooii
  • 8,588
  • 14
  • 66
  • 90
0

Try with this function:

function validate() {
    var field = document.getElementById("myField");
    if (field.value.replace(/ /g, "").length == 0)  {
        alert("Please enter some data (not spaces!)");
    }
}
MatuDuke
  • 4,997
  • 1
  • 21
  • 26
0

Reference from steven levithan blog on Faster javascript trim

Trim the string in javascript for leading and ending spaces with the following funciton

<script type='text/javascript'>

function validate()
{
  var str= document.getElementById('str').value;

   if(str== '' || trim(str) == '')
   { 
         alert('Invalid string'); 
         return false;
   }
   else
   {
       return true;
   } 
}
function trim (str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}
</script>
Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36
  • I am wondering why you didn't use the obvious `str = str.replace(/^\s+/, '').replace(/\s+$/, '');`. Instead you only remove the leading spaces with a regex and use a loop for the trailing spaces, where the test is even negative. (\S instead of \s). This makes it a bit hard to read. – Leif Mar 13 '12 at 12:38
  • @Leif `http://blog.stevenlevithan.com/archives/faster-trim-javascript` blog.stevenlevithan.com -- Faster JavaScript Trim – Naveen Kumar Mar 13 '12 at 12:46
  • That's amazing. You should mention this in your answer. – Leif Mar 13 '12 at 12:53
  • Now look at the references edit from 2008-02-04. He is using a positive check (\s) within a while loop. That's what I had in mind, if the loop had to be kept. – Leif Mar 13 '12 at 13:15