-1

I am trying to interrupt a form submission to test field for alphanumeric characters. After googling i found a lot of this implementation for regex that everyone claims works great...

if( !jQuery('input[name=myUsername]').val().test(/^[a-zA-Z0-9]+/) ) {
        alert('ERROR: Your username contains invalid characters. Please use numbers and letters only. No spaces, no punctuation.');
        jQuery('input[name=myUsername]').focus();
        return false;
}

However, this ONLY returns false and creates an alert if the value STARTS with a non-alphanumeric character. If i enter "bo$$" it allows it as alphanumeric even tho $ is not an alphanumeric character... If i enter "$$ob" it fails and alerts.

How do i fix this so that it will fail for ANY invalid character in the entire value? I've tried .match() instead of .test() but same issue im assuming it's something in the regex that is wrong

1
  • 2
    try /^[a-zA-Z0-9]+$/ Commented Jan 28, 2015 at 6:50

2 Answers 2

2
^[a-zA-Z0-9]+$

put $ the end anchor to limit that.Without $ your regex will make a partial match.

$ assert position at end of a line

bo$$ will make a partial match upto bo as $ is not there.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't normally compromise my anonymity on down votes, but in this case I'll make an exception although I'll delete the comment after a few hours. Downvote as the original was unclear / gave the wrong impression. Your edit then fixed it, so I have reversed the downvote.
Fair enough - I was rushing a bit. You're right - a comment is usually helpful / only fair.
0

Use anchor $ to avoid matching unwanted character at the end:

/^[a-zA-Z0-9]+$/

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.