Regex in C# for password - c#

I have regex for validating user passwords to contain:
atleast 8 alpha numberic characters
1 uppercase letter
1 lowercase letter
1 digit
Allowed special charaters !##$%*.~
I am using the following regex:
(?=(.*\w){8,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*[0-9]){1,})(?=(.*[!##$%*.~]))
This however does not prevent the user from entering other special characters
such as <,> , &.
How do I can restrict the allowed number of special characters?

A single regex to validate everything will ultimately look like line noise.
Instead I suggest:
Use simple String functions to test length
Use Regex to test for character inclusion and validity

^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])[a-zA-Z0-9!##$%*.~]{8,}$
The anchoring (^ and $) is important, by the way.

Related

Underscore in regex not validating

How do I add underscore as a part of my regex string.
Here is my string that checks for uppercase, lowercase, numbers and special characters. The rest of the special characters work. Validation isn't working for underscores.
#"^[^\s](?=(.*[A-Za-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?=(.*[!##$%^&*()-+=\[{\]};:<>|_.\\/?,\-`'""~]{1,})).*[^\s]$"
Any ideas?
Thanks
This is the regex that AWS Cogito uses, it should apply to your situation:
#"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\^$*.\[\]{}\(\)?\-“!##%&\/,><’:;|_~`])\S{8,99}$"
You can check regexes at http://regexstorm.net, it's faster than building your application everytime.
I've approached it like this: I took your requirements and made them into separate positive lookaheads:
Check for:
uppercase (?=.*[A-Z])
lowercase (?=.*[a-z]) (note that I broke A-Z and a-z up into separate groups)
numbers (?=.*\d)
special characters (?=.*[!##$%^&*()-+=\[{\]};:<>|_.\\/?,\-`'""~])
You can then combine them in any order and I've combined them in the same order as I listed them above and anchored it with the beginning of the line using ^. Don't add any extra matches before, in-between or after the groups in your requirement that could cause the regex to enforce a certain ordering of the groups:
The lookahead for any non-word character \W makes it impossible to match Underscore1_ since it will only match on "anything other than a letter, digit or underscore" - which is all Underscore1_ contains.
The starting [^\s] (and ending [^\s]) that consumes one character is likely destroying a lot of good matches. Underscore1_ or _1scoreUnder shouldn't matter, but if you start with _ and consume it with [^\s] like you do, the later lookahead for a special character will fail (unless you have a second special character in the password).
#"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!##$%^&*()-+=\[{\]};:<>|_.\\/?,\-`'""~])"
If you have a minimum length requirement of, say, 7 characters, you just have to add .{7,}$ to the end of the regex, making it:
#"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!##$%^&*()-+=\[{\]};:<>|_.\\/?,\-`'""~]).{7,}$"
Without a minimum length, a password of one character from each group will be enough, and since there are 4 groups, a password with only 4 characters will pass the filter.
I see no point in putting an upper length limit into the regex. If the user interface has accepted a string that is thousands of characters long, then why reject it for being too long later? The length of what you store is probably going to be much smaller anyway since you'll be storing the bcrypt/scrypt/argon2/... encoded password.
Suggestion: Also add space (or even whitespaces) to the list of special characters.
In you regexp add underscore in 3rd Capturing Group regex101
#"^[^\s](?=(.*[A-Za-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W_]){1,})(?=(.*[!##$%^&*()-+=\[{\]};:<>|_.\\/?,\-`'""~]{1,})).*[^\s]$"

Update regular expression to only allow single spaces [duplicate]

Right now I have a regex that prevents the user from typing any special characters. The only allowed characters are A through Z, 0 through 9 or spaces.
I want to improve this regex to prevent the following:
No leading/training spaces - If the user types one or more spaces before or after the entry, do not allow.
No double-spaces - If the user types the space key more than once, do not allow.
The Regex I have right now to prevent special characters is as follows and appears to work just fine, which is:
^[a-zA-Z0-9 ]+$
Following some other ideas, I tried all these options but they did not work:
^\A\s+[a-zA-Z0-9 ]+$\A\s+
/s*^[a-zA-Z0-9 ]+$/s*
Could I get a helping hand with this code? Again, I just want letters A-Z, numbers 0-9, and no leading or trailing spaces.
Thanks.
You can use the following regex:
^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$
See regex demo.
The regex will match alphanumerics at the start (1 or more) and then zero or more chunks of a single space followed with one or more alphanumerics.
As an alternative, here is a regex based on lookaheads (but is thus less efficient):
^(?!.* {2})(?=\S)(?=.*\S$)[a-zA-Z0-9 ]+$
See the regex demo
The (?!.* {2}) disallows consecutive spaces and (?=.*\S$) requires a non-whitespace to be at the end of the string and (?=\S) requires it at the start.

Regular expression for SSN that accept one extra character

I am looking for something for Social Security Number which is in the form "###-##-####". I need a way that the first character can also be allowed to type "#"
How do I add that? I need it for a masked text box mask.
Try this regex:
^(#|\d\d\d-\d\d-\d\d\d\d)$
(Note: this is with the US format: ###-##-####)
The ^ and $ mean the "start" and "end" of the string, so that you can't match items in the middle of your text.
The | says "one or the other". So it will match a #, or the digits.
The following will match
123-45-6789
#
but this won't match
234-3333-14234
#123-45-6789
You can take a demo here.
Make sure when you type this into c# you use the correct character escaping:
string pattern = #"^(#|\d\d\d-\d\d-\d\d\d\d)$";
all you need is this (\d is any digit and \d is \d escaped for c# and #? means it will accept 0 or 1 #)
#?\\d\\d\\d-\\d\\d-\\d\\d\\d\\d

Basic Regular Expression for a 'generic' phone number

I need a regex (for use in an ASP .NET web site) to validate telephone numbers. Its supposed to be flexible and the only restrictions are:
should be at least 9 digits
no alphabetic letters
can include Spaces, hyphens, a single (+)
I have searched SO and Regexlib.com but i get expressions with more restrictions e.g. UK telephone or US etc.
^\s*\+?\s*([0-9][\s-]*){9,}$
Break it down:
^ # Start of the string
\s* # Ignore leading whitespace
\+? # An optional plus
\s* # followed by an optional space or multiple spaces
(
[0-9] # A digit
[\s-]* # followed by an optional space or dash or more than one of those
)
{9,} # That appears nine or more times
$ # End of the string
I prefer writing regexes the latter way, because it is easier to read and modify in the future; most languages have a flag that needs to be set for that, e.g. RegexOptions.IgnorePatternWhitespace in C#.
It's best to ask the user to fill in his country, then apply a regex for that country. Every country has its own format for phone numbers.
\+?[\d- ]{9,}
This will match numbers optionally starting with a plus and then at least nine characters long with dashes and spaces.
Although this means that dashes and spaces count towards the nine characters.
I would remove the dashes and spaces and then just use
\+?[\d]{9,}
^[0-9-+ ]+$
<asp:RegularExpressionValidator runat="server" id="rgfvphone" controltovalidate="[control id]" validationexpression="^[0-9-+ ]+$" errormessage="Please enter valid phone!" />
#"^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"
Here's what I use. This will handle generic phone number validation for most cases.
This one is super-generic, allowing only the characters you expect in a given phone number, including #. It ignores any format patterns.
#"^([\(\)\+0-9\s\-\#]+)$"

c# Regex question: only letters, numbers and a dot (2 to 20 chars) allowed

i am wrestling with my regex.
I want to allow only letters and numbers and a dot in a username, and 2 to 20 chars long
I thought of something like this
[0-9a-zA-Z]{2,20}
but then 21 chars is also ok, and that's not what i want
I suggest that you make two checks -- one for length and one for content based on the fact that you probably only want one dot in the name, rather than any number of dots. I'll assume that names like username and user.name are the only formats allowed.
This should get the content( but allows underscores as well):
^\w+(\.\w+)?$
If you don't want underscores, then you would use [0-9a-zA-Z]+ in place of \w+. To explain, it will match any string that consists of one or more word characters, followed by exactly 0 or 1 of a dot followed by one or more word characters. It must also match the beginning and end of the string, i.e., no other characters are allowed in the string.
Then you only need to get the length with a simple length check.
^[0-9a-zA-Z\.]{2,20}$
Try ^[\w\.]{2,20}$ instead.
You need to use start and end of string (^ and $), and escape the .:
^[0-9a-zA-Z\.]{2,20}$

Categories