1

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 ?

see http://jsfiddle.net/R2WZT/

Tomáš Zato
54k63 gold badges317 silver badges845 bronze badges
asked Jul 11, 2013 at 15:03
1
  • 3
    you are matching 1 to 12 characters not 1 to 10 characters.. Commented Jul 11, 2013 at 15:07

2 Answers 2

7

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.

answered Jul 11, 2013 at 15:06
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, otherwise "av" in the example matches the regex. Clicking "Replace" lower down on the page gives you "$replaced", indicating that the "av" portion is what matched. Also, shouldn't OP have {1,10} if he wants to match 1 to 10 characters?
@wlyles yes, if the plan is to match strings at most 10 characters long, then allowing 12 character strings seems suspicious :)
1

You're not setting it to match the start and end:

var reg = /^[0-9A-Za-z\+\*\.]{1,10}$/;
answered Jul 11, 2013 at 15:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.