views:

30

answers:

1

Hi there: I have the following possible string: '', or '4.', or '*.4' or '4.35' all the above format are valid, others are all invalid. basically, if I don't care the digit or word character, this is what I used in PHP for the validation:

        else if ( !ereg('^\*|.*\..*$',$bl_objver) )

Now, I would like to add some clientside validation, so I just translate it into javascript:

    var ver_reg = new RegExp("^\*|.*\..*$");
    if (ver_reg.test(obj_ver) == false)

but firebug always shows some error, like: "invalid quantifier |...*$" etc..

any suggestions?

A: 

(I'm not convinced your expression is correct, but for the moment just going with what you have.)

Using the RegExp object, you need to escape the slashes:

var ver_reg = new RegExp("^\\*|.*\\..*$");

Alternatively you can use regex literal notation:

var ver_reg = /^\*|.*\..*$/;


That answers your direct question, but...

As for the expression, well, what you definitely want to correct is the start/end anchors each applying to one side of the alternation.

i.e. you're saying <this>|<that> where <this> is ^\* and <that> is .*\..*$

What you want is ^(?:<this>|<that>)$ to ensure the start/end markers are not part of the alternatives (but using ?: since we're not capturing the group).

So /^(?:\*|.*\..*)$/ using the second example above - this fix would also need applying to the PHP version (which can use the same syntax).

I'd also question your use of . instead of \w or [^.] or similar, but without knowing what you're actually doing, I can't say for sure what makes most sense.

Hope this helps! :)

Peter Boughton
thanks, just found some explanation about this as well:http://www.regular-expressions.info/javascript.html
WilliamLou
Yeah, that's a good site - well worth reading and learning as much as you can from it. :)
Peter Boughton