-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

b747fp
  • 175
  • 3
  • 12

2 Answers2

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.

vks
  • 67,027
  • 10
  • 91
  • 124
  • 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. – J Richard Snape Jan 28 '15 at 09:59
  • 1
    Fair enough - I was rushing a bit. You're right - a comment is usually helpful / only fair. – J Richard Snape Jan 28 '15 at 10:11
0

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

/^[a-zA-Z0-9]+$/
anubhava
  • 761,203
  • 64
  • 569
  • 643