admin管理员组

文章数量:1313284

i have created this regular expression for my form validation of password feild

"/^[[A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*]{3,25}$/",

it accepts all alphanumeric characters and special characters BUT special characters only is not acceptable .

The problem is with the length check :(

it should be like the following

Valid: aaaaaaaaa 
Valid: 111111111
Valid: 11111n11111
Valid: nnnn1jkhuig
InValid: @@@@@@@@

but it is throwing error on

aaaaaaaaaaaa

as well

i have created this regular expression for my form validation of password feild

"/^[[A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*]{3,25}$/",

it accepts all alphanumeric characters and special characters BUT special characters only is not acceptable .

The problem is with the length check :(

it should be like the following

Valid: aaaaaaaaa 
Valid: 111111111
Valid: 11111n11111
Valid: nnnn1jkhuig
InValid: @@@@@@@@

but it is throwing error on

aaaaaaaaaaaa

as well

Share Improve this question edited Sep 12, 2011 at 11:13 Felix 89.6k44 gold badges151 silver badges168 bronze badges asked Sep 12, 2011 at 11:11 nidanida 834 silver badges10 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4
^(?=.*[A-Za-z0-9])[A-Za-z0-9, .!@#$%^&*()_]{6,25}$

(Tested with PHP). The explanation:

  • The string should match [A-Za-z0-9, .!@#$%^&*()_] on 6 to 25 characters
  • Somewhere in the string [A-Za-z0-9] must be present (ensuring that the string is not posed of special chars only).

You can use a zero-width positive assertion to solve this. Here's the regex, and I'll deconstruct it below.

/(?=.*[A-Za-z0-9])[A-Za-z0-9, .!@#$%^&*()_]{3,25}/

The first ponent is (?=.*[A-Za-z0-9]). The construct (?=...) is a zero-width assertion, meaning it checks something, but doesn't "eat" any of the output. If the "..." part matches, the assertion passes and the regex continues. If it does not match, the assertion fails, and the regex returns as not matching. In this case, our "..." is ".*[A-Za-z0-9]" which just says "check to see the an alphanumeric character exists in there somewhere, we don't care where".

The next ponent is [A-Za-z0-9, .!@#$%^&*()_]{3,25} and just says to match between 3 and 25 characters out of any of the valid. We already know that at least one of them is alphanumeric, because of our positive-lookahead assertion, so this is good enough.

You can not nest character classes, but I think what you meant is

/^([A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*){3,25}$/

But this will also not work because the quantifier {3,25} can also not be nested.

Try this instead

^(?=.{3,25})[A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*$

(?=.{3,25}) is a lookahead that just ensures your length requirement.

I think your regexp is a bit weird, you're enclosing a set within a set.

It should be something like /^([A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*){3,25}$/ with parenthesis to define the number.

本文标签: javascriptneed a Regex for validating alphanumeric with length 6 to 25 charactersStack Overflow