0

I'm not a regex guy, so I definitely need help on this.

All I want is to have a regular expression to validate if the user inputted on "username" will contain no spaces.

Currently, I have this structure:

if($('.username').val().length < 5) {
  $(".user_account_validation").html("Too shorty.").css('background-color', 'red');
} else if() {
}

As you can notice my else if() is still empty, and in that I want to place my validation. If the username has space I'll return a corresponding error message. Thanks!

3 Answers 3

6

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. --Jamie Zawinski

If all you want to know is if there are spaces in the input, the following will return -1 if there are no spaces in the input, and the index of the first space otherwise.

$('.username').val().indexOf(' ');

If you need a regular expression the following will return the index of the first whitespace, and -1 otherwise.

$('.username').val().search(/\s/);
Sign up to request clarification or add additional context in comments.

2 Comments

This question is a perfect counter-example of Jamie's rule. This is because the language to match here actually IS regular.
@NiklasB. I will stipulate that it is a decent place to use a Regex, and in fact if the OP asked "how do I check for valid input", I would have pointed him to a Regex, but the quote is a knee-jerk response to, "I have problem X, how do use a Regex for it?". Ideally, we should all look at every tool in our toolbox, rather than seeing everything as a nail to be pounded with a Regex hammer.
4

No need to use a regex. You can simply use $('.username').val().indexOf(' ') !== -1 to test if it contains any spaces.

Note that it does not prevent the user from entering tabs via copy&paste, but you need validation on the server side anyway, so if you check for things regular users won't enter over there, it's sufficient.

3 Comments

What about tabs, newlines, etc...?
Actually a regex would be really fitting here, why not suggest it (especially because it was asked for)?
Unless you use copy&paste or have a textarea you cannot enter tabs/newlines anyway. But you are right, if you want to block all whitespace a regex is better.
3

you could use indexOf for just ' '

else if ( $('.username').val().indexOf(' ') === -1 ) {
    //do stuff
}

but if you need to match anywhite space then use this

else if ( $('.uername').val().match(/\s/) {
    //do stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.