I would like to create a javascript regex to test a string that would accept only characters from 0 to 9, a to z, A to Z and the followings chars: + * . for a total length between 1 and 10 characters.
I did this :
var reg = /[0-9A-Za-z\+\*\.]{1,12}/;
if(!reg.test($('#vat_id').val())) {
return false;
}
but this doesn't seem to work.
I tested it on http://www.regular-expressions.info/javascriptexample.html, I can input "$av" and it returns me "successful match"
where is the mistake ?
edit : the regex seems good now :
var reg = /^[0-9A-Za-z\+\*\.]{1,10}$/;
But why i can't make it work ?
-
3you are matching 1 to 12 characters not 1 to 10 characters..Anirudha– Anirudha2013年07月11日 15:07:29 +00:00Commented Jul 11, 2013 at 15:07
2 Answers 2
If you don't "anchor" the regular expression to indicate that matches should start at the beginning and end at the end of the test string, then that is taken to mean that you want to see if the pattern can be found anywhere in the string.
var reg = /^[0-9A-Za-z\+\*\.]{1,12}$/;
With ^ at the beginning and $ at the end, you indicate that the entire string must match the pattern; that is, that no characters appear in the string other than those that contribute to the match.
2 Comments
{1,10} if he wants to match 1 to 10 characters?You're not setting it to match the start and end:
var reg = /^[0-9A-Za-z\+\*\.]{1,10}$/;