3

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;
  }
4
  • 1
    Regular Expressions. Also, you're trimming the string, so how could there be a space at the beginning of it? Commented Apr 7, 2013 at 4:22
  • I use trim bt in db it dont remove space Commented Apr 7, 2013 at 4:35
  • 1
    It sounds like you're saying that you want to find out if a string has a space at the beginning of it, but you're trimming that space off before you check. So the solution would be to not trim the string... Commented Apr 7, 2013 at 4:55
  • @Nathan Bouscal you was right.thanks Commented Apr 7, 2013 at 5:16

3 Answers 3

8

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)
};
Sign up to request clarification or add additional context in comments.

5 Comments

indexOf would be the fastest method (versus regex to check for a space), however whitelisting what they CAN use via regex is probably safer than blacklisting what they cannot.
@Blender i use first method but it works in first case example if i give this string then it does not work ` space abc def`
@AzamAlvi: Change === to !==.
@Blender does not work, open this jsfidle link jsfiddle.net/azamalvi/Lsg45/1
@AzamAlvi: Works just fine for me. Try getting rid of $.trim(), as you're probably adding spaces to the beginning/end to test it.
4

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.

3 Comments

it's same as my function does. no alrt if space is given in start
check out the link to the jsFiddle I posted, it works as expected.
I think you should read up on trim() - it removes the spaces from the beginning and ending of a string, so when you use var username = $.trim($('#username').val()); the space is removed from the field before you check it.
1

why you don't use something like this?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.