0

I have these scripts...

 Name: <input type="text" id="inputName" onblur="verifyName(this.value)">

 <script type="text/javascript">
    function verifyName(nameInput)
    {
       if(nameInput=="")
       {
          // error
          alert('please enter your name');
       }
       else
       {
          // accepted
       }
    }
 </script>

This will display an error if the user don't want to enter his/her name on the textbox.

What if the user is lazy and he/she will enter " " (a space or more) as a name? This can be accepted by the JavaScript. It will return false on the if condition.

But I want the user not to enter only spaces. Is there any way to do that?

Note: Any number of spaces (without any letters) inputted are invalid.


If the user inputs one of the texts below, JavaScript should accepts/rejects the input as follows...

"John" --> valid
"" --> invalid
"John Doe" --> valid
"    " --> invalid
"John     Doe" --> valid (can be edited to remove too many spaces)
"      Kim" --> valid (can be edited to remove too many spaces)
" " --> invalid
Mai
  • 363
  • 3
  • 16
  • This question doesn't asks about trimming text but for this question, trimming is the solution... – Mai Feb 17 '15 at 03:47

4 Answers4

0

Trim the string before you do the checking. See below

if(nameInput.trim()=="")
{
     // error
     alert('please enter your name');
}
else
{
 // accepted
}
BenW
  • 1,393
  • 1
  • 16
  • 26
0

One (of quite a few) possible implementation of your function uses regular expressions:

function verifyName(nameInput) {
    return input.match(/\w{1,12}/) === null ? false : true;
    //                       ^^
    //    Or some other sensible limitation to the length of a name. 
}
jdphenix
  • 15,022
  • 3
  • 41
  • 74
0
function verifyName(nameInput)
{
   nameInput = nameInput.trim();
   if(nameInput=="")
   {
      // error
      alert('please enter your name');
   }
   else
   {
      // accepted
   }
}

The trim() function will remove all spaces. If there are only spaces in the var, trim() with return "".

Anuja
  • 124
  • 2
  • 6
0

You can make use of regular expression to replace all the spaces from the string and then check its length. If there is at least one character remaining after removing all the spaces - that's your valid case right?

testInput = function(){

  var inpStr = $('#txtInp').val();
  
  
var teststr = inpStr.replace(/\s/g, "");
 
  //$('#testStrDiv').text(teststr);
  
  if((teststr.length)&&(teststr.length>0))
    {
      $('#divOutp').html('<b>Valid! </b>');
      }
  else{
        $('#divOutp').html('<b>Invalid! </b>');
      }
  
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtInp" />

<input type="button" onclick="testInput()" value="test" />
<div id="testStrDiv" />
<div id="divOutp" />
amitthk
  • 1,115
  • 1
  • 11
  • 19