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;
}
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;
}
Share
Improve this question
asked Apr 7, 2013 at 4:21
Azam AlviAzam Alvi
7,0558 gold badges67 silver badges89 bronze badges
4
- 1 Regular Expressions. Also, you're trimming the string, so how could there be a space at the beginning of it? – user788472 Commented Apr 7, 2013 at 4:22
- I use trim bt in db it dont remove space – Azam Alvi 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... – user788472 Commented Apr 7, 2013 at 4:55
- @Nathan Bouscal you was right.thanks – Azam Alvi Commented Apr 7, 2013 at 5:16
3 Answers
Reset to default 8Just 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)
};
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.
why you don't use something like this?
if(string.indexOf(space) > -1){
return true
}