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\-\#]+)$"
Related
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]$"
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.
I already gone through many post on SO. I didn't find what I needed for my specific scenario.
I need a regex for alpha numeric string.
where following conditions should be matched
Valid string:
ameya123 (alphabets and numbers)
ameya (only alphabets)
AMeya12(Capital and normal alphabets and numbers)
Ameya_123 (alphabets and underscore and numbers)
Ameya_ 123 (alphabets underscore and white speces)
Invalid string:
123 (only numbers)
_ (only underscore)
(only space) (only white spaces)
any special charecter other than underscore
what i tried till now:
(?=.*[a-zA-Z])(?=.*[0-9]*[\s]*[_]*)
the above regex is working in Regex online editor however not working in data annotation in c#
please suggest.
Based on your requirements and not your attempt, what you are in need of is this:
^(?!(?:\d+|_+| +)$)[\w ]+$
The negative lookahead looks for undesired matches to fail the whole process. Those are strings containing digits only, underscores only or spaces only. If they never happen we want to have a match for ^[\w ]+$ which is nearly the same as ^[a-zA-Z0-9_ ]+$.
See live demo here
Explanation:
^ Start of line / string
(?! Start of negative lookahead
(?: Start of non-capturing group
\d+ Match digits
| Or
_+ Match underscores
| Or
[ ]+ Match spaces
)$ End of non-capturing group immediately followed by end of line / string (none of previous matches should be found)
) End of negative lookahead
[\w ]+$ Match a character inside the character set up to end of input string
Note: \w is a shorthand for [a-zA-Z0-9_] unless u modifier is set.
One problem with your regex is that in annotations, the regex must match and consume the entire string input, while your pattern only contains lookarounds that do not consume any text.
You may use
^(?!\d+$)(?![_\s]+$)[A-Za-z0-9\s_]+$
See the regex demo. Note that \w (when used for a server-side validation, and thus parsed with the .NET regex engine) will also allow any Unicode letters, digits and some more stuff when validating on the server side, so I'd rather stick to [A-Za-z0-9_] to be consistent with both server- and client-side validation.
Details
^ - start of string (not necessary here, but good to have when debugging)
(?!\d+$) - a negative lookahead that fails the match if the whole string consists of digits
(?![_\s]+$) - a negative lookahead that fails the match if the whole string consists of underscores and/or whitespaces. NOTE: if you plan to only disallow ____ or " " like inputs, you need to split this lookahead into (?!_+$) and (?!\s+$))
[A-Za-z0-9\s_]+ - 1+ ASCII letters, digits, _ and whitespace chars
$ - end of string (not necessary here, but still good to have).
If I understand your requirements correctly, you need to match one or more letters (uppercase or lowercase), and possibly zero or more of digits, whitespace, or underscore. This implies the following pattern:
^[A-Za-z0-9\s_]*[A-Za-z][A-Za-z0-9\s_]*$
Demo
In the demo, I have replaced \s with \t \r, because \s was matching across all lines.
Unlike the answers given by #revo and #wiktor, I don't have a fancy looking explanation to the regex. I am beautiful even without my makeup on. Honestly, if you don't understand the pattern I gave, you might want to review a good regex tutorial.
This simple RegEx should do it:
[a-zA-Z]+[0-9_ ]*
One or more Alphabet, followed by zero or more numbers, underscore and Space.
This one should be good:
[\w\s_]*[a-zA-Z]+[\w\s_]*
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.
Similar to this topic.
I am trying to validate a username with the following restrictions:
Must start with a letter or number
Must be 3 to 15 characters in length
Symbols include: . - _ ( ) [ ]
Symbols cannot be adjacent, but letters and numbers can
Edit:
Letters and numbers are a-z A-Z 0-9
Been stumped for a while. I'm new to regex.
As an optimization to Mark's answer:
^(?=.{3,15}$)([A-Za-z0-9][._()\[\]-]?)*$
Explanation:
(?=.{3,15}$) Must be 3-15 characters in the string
([A-Za-z0-9][._()\[\]-]?)* The string is a sequence of alphanumerics,
each of which may be followed by a symbol
This one permits Unicode alphanumerics:
^(?=.{3,15}$)((\p{L}|\p{N})[._()\[\]-]?)*$
This one is the Unicode variant, plus uses non-capturing groups:
^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)*$
It is not so clean to express a set of unrelated rules in a single regular expression, but it can be done by using lookaround assertions (Rubular):
#"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$"
Explanation:
(?=[A-Za-z0-9]) Must start with a letter or number
(?!.*[._()\[\]-]{2}) Cannot contain two consecutive symbols
[A-Za-z0-9._()\[\]-]{3,15} Must consist of between 3 to 15 allowed characters
You might want to consider if this would be easier to read and more maintable as a list of simpler regular expressions, all of which must validate successfully, or else write it in ordinary C# code.