Regular expression for DataAnnotation for Password - c#

We have a requirement to make sure password conforms to the specific strength format (this is configured in web.config). Requirements are that password must contain certain number of capital characters and certain number of non-alphanumeric characters. I want to annotate my Password property with regular expression that validates password to make sure password contains x number of CAPS and y number of non-alpha chars. Please help with regular expression.

Checking multiple conditions like this in a single regex is best accomplished using lookaheads, for example say you want 3 capital characters and 4 non-alpha characters, you could use the following regex:
^(?=(?:.*[A-Z]){3})(?=(?:.*[^a-zA-Z]){4})
Explanation: first, lets think about what a regex would look like that only checks the first condition. To match 3 uppercase characters we can use the following:
(?:.*[A-Z]){3}
We can still check this condition by dropping it inside of a lookahead, which is what the (?=...) does, so now (?=(?:.*[A-Z]){3}) checks this condition without consuming any characters. At this point we can check the second condition using (?:.*[^a-zA-Z]){4}. I put this second condition inside of a lookahead as well so that adding more checks is straightforward.
Note that the current regex won't actually match any characters, it will match the beginning of the string (zero characters) if all conditions match, otherwise the match will fail. If you want it to actually consume characters as well, just add .* to the end.

I found a good article that solves it for me
http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/

Related

Regular expression thingy

I would like to create a custom regular expression. Which shall track that the first character of a username should be an alphabet.
Followed by alphanumeric or can have maximum one occurrence of a special character (- or _). I can check for username starts with the alphabet with this ^[a-zA-Z]+$ but not sure what to do to check at most one occurrence of a special character. Any ideas are welcome.
Thanks
From what I understood of your post, you want the following to match.
a-afdsafd
aafdsafd
aafdsa_fd
aafdsa-fd
aAfdsa-FD
And the following to not match:
aa-dsa-fd
aa-dsa_fd
-afdsafd
_afdsafd
Try /^[a-z](?:(?![a-z]+[\-_])[\-_])?[a-z]+(?:(?<![a-z]+[\-_])[\-_]?)[a-z]+?$/i
The i modifier enables case-insensitive matching.
The ^ and $ anchors ensure that the entire string matches our regex.
[a-z] checks that the first character is an alphabet.
(?:(?![a-z]+[\-_])[\-_])?) looks ahead to check that there is no "special character" used later and if there is none, we optionally match one special character.
[a-z]+ Match one or more alphabets.
(?:(?<![a-z]+[\-_])[\-_]?) does the same thing as 4 except it looks behind.
[a-z]+? Optionally match one or more alphabets.
https://regexr.com/3t86l
Edit: I noticed that aAfdsaFd_ should also match. The above does not match this. Slightly modifying #Wiktor Stribiżew's comment, ^[a-zA-Z][a-zA-Z0-9]*(?:[-_][a-zA-Z0-9]*)?$ seems to work fine with all cases. That's cleaner and more efficient. All credit to #Wiktor Stribiżew.
You could match an upper or lowercase character from the start of the string ^[a-zA-Z], match zero or more times alphanumeric [a-zA-Z0-9]* followed by an optional hyphen or underscore [-_]?.
At the end match zero or more times alphanumeric [a-zA-Z0-9]*$ until the end of the string.
^[a-zA-Z][a-zA-Z0-9]*[-_]?[a-zA-Z0-9]*$

Regular expression for adding special character to phone number

I have added the following regular expression for validating a mobile phone number:
(^07[1,2,3,4,5,7,8,9][0-9]{7,8}$)
I want to allow the user to enter a # character too and I'm not sure where to fit it in. They may need to enter # character after they have dialed a number, or at the beginning of a number to dial a direct number or an extension.
First, your current regex matches 'numbers' of the format 07,12345678 as well. So you need to change [1,2,3,4,5,7,8,9] to [1-9] (when you have a - between two characters in a character class, it usually means that there's a range)
If you want to accept an optional # character, you can use the ? quantifier which means 0 or 1 times.
^#?07[1-9][0-9]{7,8}#?$
regex101 demo
Except that, as you can see in the demo, it will also match numbers with two hashes; one at the front and one at the end. One option to circumvent this is to use some conditionals (which C# can support).
^(#)?07[1-9][0-9]{7,8}(?(1)|#?)$
regex101 demo
(?(1)|#?) basically means that if the first hash was matched, then nothing more should be matched. Otherwise, if no hash was initially matched, then it can match a hash, if there is one at the end of the number.
In C#, it will be a bit like this:
Regex.Match(myString, #"^(#)?07[1-9][0-9]{7,8}(?(1)|#?)$");
Or you could use a negative lookahead to make sure there's never more than one hash in the number:
^(?!.*#.*#.*$)#?07[1-9][0-9]{7,8}#?$

Password Regex (client side javascript)

I need a regex for the following criteria:
Atleast 7 alphanumeric characters with 1 special character
I used this:
^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$!%^&+=]).*$
It works fine if I type Password1! but doesnt work for PASSWORD1!.
Wont work for: Stmaryshsp1tal!
I am using the Jquery validation plugin where I specify the regex.
When I use a regular expression validator and specify the following regex:
^.*(?=.{7,})(?=(.*\W){1,}).*$
It works perfectly without any issues. When I set this regex in the Jquery validation I am using it doesnt work.
Please can someone shed some light on this? I want to understand why my first regex doesnt work.
(?=.\d)(?=.[a-z])
tries to match a digit and an alphanumeric character at the same place. Remember that (?= ... ) does not glob anything.
What you want is probably:
^(?=.*\W)(?=(.*\w){7})
This is exactly the same as veryfying that your string both matches ^.*\W (at least one special character) and ^(.*\w){7}) (7 alphanumeric characters. Note that it also matches if there are more.
Try this regex:
\S*[##$!%^&+=]+\S*(?<=\S{7,})
EDIT3: Ok, this is last edit ;).
This will match also other special characters. So if you wan't limit the number of valid characters change \S to range of all valid characters.
Here is the regex , I think it can handle all possible combination..
^(?=.{7,})\w*[.##$!%^&+=]+(\w*[.##$!%^&+=]*)*$
here is the link for this regex, http://regexr.com?2tuh5
As a good tool for quickly testing regular expressions I'd suggest http://regexpal.com/ (no relations ;) ). Sometimes simplifying your expression helps a lot.
Then you might want to try something like ^[a-zA-Z0-9##$!%^&+=]{7,}$
Update 2 now including digits
^.*(?=.{7,})(?=.*\d)(?=.*[a-zA-Z])(?=.*[##$%^&+=!]).*$
This matches:
Stmarysh3sptal!, password1!, PASSWORD1P!!!!!!##^^ASSWORD1, 122ss121a212!!
... but not:
Password1, PASSWORD1PASSWORD1, PASSWORD!, Password!, 1221121212!! etc
The reason it matches Password1! but not PASSWORD1! is this clause:
(?=.*[a-z])
That requires at least one lowercase letter in the password. The pattern says that the password must be at least 7 characters long, and contain both uppercase and lowercase letters, at least one number, and at least one of ##$!%^&+=. PASSWORD1! fails because there are no lowercase letters in it.
The second pattern accepts PASSWORD1! because it's a far, far weaker password requirement. All it requires is that the password is 7+ characters and has at least one special character in it (other than _). The {1,} is unnecessary, by the way.
If I were you, I'd avoid weakening the password and just leave it as it is. If I wanted to allow all-lowercase or all-uppercase passwords for some reason, I'd simply change it to
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[##$!%^&+=]).{7,}$
...thus not weakening the password requirements any more than I had to.

.NET Regular expression which check length and non-alphanumeric characters

I need Regexp to validate string has minimum length 6 and it is contains at least one non-alphanumeric character e.g: "eN%{S$u)", "h9YI!>4j", "{9YI!;4j", "eN%{S$usdf)", "dfh9YI!>4j", "ghffg{9YI!;4j".
This one is working well ^.*(?=.{6,})(?=.*\\d).*$" but in cases when string does not contain any numbers(e.g "eN%{S$u)") it is not working.
^(?=.{6})(.*[^0-9a-zA-Z].*)$
We use positive lookahead to assure there are at least 6 characters. Then we match the pattern that looks for at least one non-alphanumeric character ([^0-9a-zA-Z]). The .*'s match any number of any characters around this one non-alphanumeric character, but by the time we've reached here we've already checked that we're matching at least 6.
^.*(?=.{6,})(?=.*\\d).*$"
is the regex you tried. Here are some suggestions:
You don't need to match more than 6 characters in the lookahead. Matching only 6 here does no restrict the rest of the regular expression from matching more than 6.
\d matches a digit, and (?=.*\\d) is a lookahead for one of them. This is why you are experiencing the problems you mentioned with strings like eN%{S$u).
Even if the point above wasn't incorrect and the regular expression here was correct, you can combine the second lookahead with the .* that follows by just using .*\\d.*.
marcog's answer is pretty good, but I'd do it the other way around so that it's easier to add even more conditions (such as having at least one digit or whatever), and I'd use lazy quantifiers because they are cheaper for certain patterns:
^(?=.*?[^0-9a-zA-Z]).{6}
So if you were to add the mentioned additional condition, it would be like this:
^(?=.*?[^0-9a-zA-Z])(?=.*?[0-9]).{6}
As you can see, this pattern is easily extensible. Note that is is designed to be used for checking matches only, its capture is not useful.
Keep it easy.
// long enough and contains something not digit or a-z
x.Length >= 6 && Regex.IsMatch(x, #"[^\da-zA-Z]")
Happy coding.
Edit, pure "regular expression":
This first asserts there are 6 letters of anything in the look-ahead, and then ensures that within the look-ahead there is something that is not alpha-numeric (it will "throw away" up to the first 5 characters trying to match).
(?=.{6}).{0,5}[^\da-zA-Z]
What about that(fixed): ^(?=.{6})(.*[^\w].*)$
Check this out http://www.ultrapico.com/Expresso.htm it is cool tool which could help you a lot in Regexps learning.

How Can I Check If a C# Regular Expression Is Trying to Match 1-(and-only-1)-Character Strings?

Maybe this is a very rare (or even dumb) question, but I do need it in my app.
How can I check if a C# regular expression is trying to match 1-character strings?
That means, I only allow the users to search 1-character strings. If the user is trying to search multi-character strings, an error message will be displaying to the users.
Did I make myself clear?
Thanks.
Peter
P.S.: I saw an answer about calculating the final matched strings' length, but for some unknown reason, the answer is gone.
I thought it for a while, I think calculating the final matched strings length is okay, though it's gonna be kind of slow.
Yet, the original question is very rare and tedious.
a regexp would be .{1}
This will allow any char though. if you only want alpanumeric then you can use [a-z0-9]{1} or shorthand /w{1}
Another option its to limit the number of chars a user can type in an input field. set a maxlength on it.
Yet another option is to save the forms input field to a char and not a string although you may need some handling around this to prevent errors.
Why not use maxlength and save to a char.
You can look for unescaped *, +, {}, ? etc. and count the number of characters (don't forget to flatten the [] as one character).
Basically you have to parse your regex.
Instead of validating the regular expression, which could be complicated, you could apply it only on single characters instead of the whole string.
If this is not possible, you may want to limit the possibilities of regular expression to some certain features. For instance the user can only enter characters to match or characters to exclude. Then you build up the regex in your code.
eg:
ABC matches [ABC]
^ABC matches [^ABC]
A-Z matches [A-Z]
# matches [0-9]
\w matches \w
AB#x-z matches [AB]|[0-9]|[x-z]|\w
which cases do you need to support?
This would be somewhat easy to parse and validate.

Categories

Resources