Azam Alvi
Azam Alvi

Reputation: 7055

Check Space in String

I want to check that if my username contains space so then it alert so i do this it work but one problem i am facing is that if i give space in start then it does not alert.I search it but can't find solution, my code is this

var username    =   $.trim($('#r_uname').val());
var space = " ";
  var check = function(string){
   for(i = 0; i < space.length;i++){
     if(string.indexOf(space[i]) > -1){
         return true
      }
   }
   return false;
  }

  if(check(username) == true)
  {
     alert('Username contains illegal characters or Space!');
     return false;
  }

Upvotes: 3

Views: 31641

Answers (3)

doublesharp
doublesharp

Reputation: 27599

You should use a regular expression to check for a whitespace character with \s:

if (username.match(/\s/g)){
    alert('There is a space!');
}

See the code in action in this jsFiddle.

Upvotes: 4

Javid Dadashkarimi
Javid Dadashkarimi

Reputation: 89

why you don't use something like this?

if(string.indexOf(space) > -1){
     return true
  }

Upvotes: 1

Blender
Blender

Reputation: 298096

Just use .indexOf():

var check = function(string) {
    return string.indexOf(' ') === -1;
};

You could also use regex to restrict the username to a particular format:

var check = function(string) {
    return /^[a-z0-9_]+$/i.test(string)
};

Upvotes: 8

Related Questions