开发者

need a Regex for validating alphanumeric with length 6 to 25 characters

开发者 https://www.devze.com 2023-04-04 11:14 出处:网络
i have created this regular expression for my form validation of password feild \"/^[[A-Za-z0-9]+[A-Za-z0-9, .!@#$%^&*()_]*]{3,25}$/\",

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

aaaaaa开发者_运维百科aaaaaa

as well


^(?=.*[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 composed 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 component 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 component 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消