views:

26

answers:

2

Hi,

This function works in Firefox, Chrome, IE9. Doesn't work in Opera.

function isValidHex(hex) { alert(hex);
    var strPattern = /^#([0-9a-f]{1,2}){3}$/i; alert(strPattern.test(hex));
    return strPattern.test(hex);
}

The hex going in is the same. The result of strPatter.test returns false in Opera and true in Firefox.

Tested.

#000000
#ffffff

Any ideas?

+1  A: 

This regex is incorrect. #1234 would be correct too in this regex. User the regex /^#([a-zA-Z0-9]{3}|[a-zA-Z0-9]{6})$/.

joni
This doesn't really address the issue of what's going on in Opera, and as such, should probably be a comment (and there already is one)
David Hedlund
But that does not explain why it does not work in Opera...
Felix Kling
@David Hedlund Sorry, missunderstood the question
joni
+2  A: 

If you swap the multipliers around, it works in Opera also:

function isValidHex(hex) {
  var objPattern = /^#([0-9a-f]{3}){1,2}$/i;
  return objPattern.test(hex);
}

You would want to do that anyway, so that you match one or two groups of three digits (i.e. 3 or 3+3 characters), not three groups of one or two digits (i.e. 1+1+1, 2+1+1, 2+2+1 or 2+2+2 characters).

(Note that I also renamed the varaible from strPattern to objPattern as it contains a regular expression object, not a string. If you are using hungarian notation to specify the data type, the prefix has to match the actual data type, or it's only contraproductive.)

Guffa
That makes me seriously wonder why one works in Opera and the other not.
Joey