views:

389

answers:

2

Hi I'm trying to setup a RegexpValidator that only accepts a string of alphanumeric characters between 6-30 characters long and requires one number. I'm new to Regular Expressions and everything I've tried seems to keep returning an invalid ValidationRsultEvent. Here's a chunk of code:

<mx:RegExpValidator id="regexValidator" source="{passwordInput}" property="text"
                        triggerEvent="" valid="onPasswordValidate(event)" invalid="onPasswordValidate(event)" />

private function validateRegister():void
{
  regexValidator.expression = "^(?=.*(\d|\W)).{6,30}$";
  regexValidator.validate();
}
+1  A: 

I'm not sure what would be causing the Validation error, but as far as your regular expression goes, to match alphanumeric strings with at least one number try ^(?=.*\d)\w{6,30}$

^         # Match begining of string
(?=.*\d)  # Lookahead, assert there is any number of characters followed by a digit
\w{6,30}  # \w matches letters, digits and the underscore character, 6-30 of them
$         # Match End of string

If you want to only match letters and numbers, instead of \w you can use [0-9a-zA-Z].

Your current regular expression ^(?=.*(\d|\W)).{6,30}$ is matching any string that contains at least one character other than [a-zA-Z_] (\d|\W matches a digit, or "non-word" character), that is between 6 and 30 characters long, which does not necessarily meet the requirements you specified.

gnarf
Exceptional explanation, gnarf!
macke
Thanks alot! Escaping did the trick.
BlueDude
+1  A: 

According to the ActionScript manual the backslash is a reserved character. Your expression should therefore look like

"^(?=.*(\\d|\\W)).{6,30}$"
Jens
Only if you want to actually match the backslash character do you need double backslashes. I don't think it applies in this case.
macke
@macke: Backslahes have special meaning in regular expressions, too. In this case, the expression should contain "\d" as a shortcut for digits, but unless you escape the backslash, it just contains a "d" or whatever "\d" means in ActionScript.
Jens
I know, I think you may have misread my comment. However, I think you're correct after all. I missed that the expression is defined as a string, and in strings the backslash definately needs to be escaped in order to produce the expected result. Usually, regexps are defined using the /expression/options syntax in which case backslashes should not be escaped (unless you actually want to match backslashes). Anyhow, I stand corrected!
macke