Regex validation for email with specific condition - c#

Currently I am using below code to validate email
public static bool IsValidEmail(string email)
{
var r = new Regex(#"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
return !string.IsNullOrEmpty(email) && r.IsMatch(email);
}
Now want to validate this "abc#a.bb.com" email as valid email id. what change needs to be done in regex?

Using this Regex is not the best way to validate an Email.
But, correcting your Regex to the pattern you asked, it would be like this:
var r = new Regex(#"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z\.])+[.a-zA-Z]{2,9})$");
Still insisting on the regex, you can find a more complete pattern in: https://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
I encourage you to use Microsoft documentation for email address as suggested by #Jeremy Lakeman -> https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress.trycreate?view=net-5.0

Related

How to limit which characters are permitted in strings?

I'm currently making a user class in c# that contains a first name, last name, username and email.
The username can only contain numbers [0-9], lower-case letters [a-z] and underscores '_'
The email can only contain [a-z], [A-Z], [0-9], as well as dot '.', comma ',', underscore '_' and hyphen '-'
How are these limitations set to strings in c#?
You could do this logic in the setters of the properties.
ex:
private string _firstName;
public string FirstName
{
get { return this._firstName; }
set
{
if (Regex.Match(value, YOUR_REGEX).Success)
this._firstName = value;
}
}
Sounds like the goal of this project is to get you to know how to use Regular Expressions. A good online resource for this which contains common patterns and testing is located at the Regular Expression Library
The simple email validation requirement you have can also be done with RegEx, but is actually incorrect as it will allow invalid addresses through; commas can be in an email address but they would need to be quoted which your pattern does not allow. The specifications for the local portion of an email address is probably one of the most poorly implemented standards on the internet.
For future reference, a cheat for checking email addresses within .Net is to use the MailAddress class of the System.Net.Mail namespace. You can use a try...catch routine to see if the submitted address can be converted. The only problems to be aware of using this is it will allow addresses through which most people would not consider to be valid even though they are; such as a server name without an extension (.com etc).
private bool isValidEmail (string emailAddress) {
bool ReturnValue;
try {
MailAddress ma = new MailAddress(emailAddress);
ReturnValue = true;
}
catch (Exception) { ReturnValue = false; }
return ReturnValue;
}

How to write a data annotation to check if email address found in string and fail on it

I have the following code but it's not quite working... Any ideas where i'm going wrong? It seems to be failing when there is a carriage return in the string? (see fiddles at bottom)
[RegularExpression(#"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*#((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3})))).)*$", ErrorMessage = "Please do not include an email address in your description.")]
Context
People are writing descriptions and also placing email addresses in them, for example:
"Hi there i'm bob, here is my email: example#exampele.com. Hope you
havea great day at my party."
I need to check that string and see that there is an email, and then not allow it to be submitted. (I'm using Entity framework and data annotations alongside the jquery validation in ASP .NET MVC 5... This is why i mentioned Data annotation usage.
Note:
I took the inversion technique from here:
Jquery validation on matching 'password' and 'admin' not working
And the email validation from here:
Best Regular Expression for Email Validation in C#
Attempts:
The following string:
http://pastebin.com/00BE7tUW
will show the error, whereas this will not:
http://pastebin.com/i69uxzRf
So something is a little wrong in the expression considering there is no email in it?
Fiddle:
Not working: https://regex101.com/r/zL7xD7/1
Working: https://regex101.com/r/hJ8fJ9/1
Working with email: https://regex101.com/r/dB3cU2/1
Have you tried something like this:
bool invalid = false;
public bool IsValidEmail(string strIn)
{
invalid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
try {
strIn = Regex.Replace(strIn, #"(#)(.+)$", this.DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException) {
return false;
}
if (invalid)
return false;
// Return true if strIn is in valid e-mail format.
try {
return Regex.IsMatch(strIn,
#"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException) {
return false;
}
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try {
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException) {
invalid = true;
}
return match.Groups[1].Value + domainName;
}
The IsValidEmail method returns true if the string contains a valid email address and false if it does not, but takes no other action.
To verify that the email address is valid, the IsValidEmail method calls the Regex.Replace(String, String, MatchEvaluator) method with the (#)(.+)$ regular expression pattern to separate the domain name from the email address. The third parameter is a MatchEvaluator delegate that represents the method that processes and replaces the matched text.
Then you would check the email address by doing something like:
IsValidEmail(emailAddress)
Does this work for you?
The . needed to be replaced by [\S\s]
[RegularExpression(#"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*#((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))))[\S\s])*$", ErrorMessage = "Please do not include an email address in your field description.")]
source: Regular expression is not matching new lines

Microsoft Exchange Services - How to get exact match using Resolve

Here is a question related to a Microsoft Exchange-integration.
I am calling the Microsoft Exchange Services-method ResolveName (string):
I am passing in a username, e.g. myusername , and I get two matches -one match with the username myusername and one with myusername2.
Now the question is: Is there any possibility to do a call that only returns direct matches, so that only matches with the exact username are returned?
Here follows the code:
:
var service = Service.GetService();
username = Regex.Replace(username, ".*\\\\(.*)", "$1", RegexOptions.None);
var resolvedNames = service.ResolveName(username);
foreach (var resolvedName in resolvedNames)
{
mailboxname = resolvedName.Mailbox.Address;
}
That method actually resolves e-mail addresses, so for an exact match you'd need to do something like this.
string username = "myUserName";
string domain = "myDomain.com";
string emailAddress = username + "#" + domain;
NameResolutionCollection resolvedContactList = _service.ResolveName(emailAddress);
If you cannot specify the 'username' any further than myusername (as Amicable's answer assumes you can do) then the only thing to do is write a wrapper around ResolveName that again matches all results against your search string, this time requiring an exact match.
And for doing so you would have to parse the domain name off again, because you get the full primary SMTP email address returned in .Mailbox.Address.
I'm doing the exact same thing in my Delphi code ;-)

Regex matching dynamic words within an html string

I have an html string to work with as follows:
string html = new MvcHtmlString(item.html.ToString()).ToHtmlString();
There are two different types of text I need to match although very similar. I need the initial ^^ removed and the closing |^^ removed. Then if there are multiple clients I need the ^ separating clients changed to a comma(,).
^^Client One- This text is pretty meaningless for this task, but it will exist in the real document.|^^
^^Client One^Client Two^Client Three- This text is pretty meaningless for this task, but it will exist in the real document.|^^
I need to be able to match each client and make it bold.
Client One- This text is pretty meaningless for this task, but it will exist in the real document.
Client One, Client Two, Client Three- This text is pretty meaningless for this task, but it will exist in the real document.
A nice stack over flow user provided the following but I could not get it to work or find any matches when I tested it on an online regex tester.
const string pattern = #"\^\^(?<clients>[^-]+)(?<text>-.*)\|\^\^";
var result = Regex.Replace(html, pattern,
m =>
{
var clientlist = m.Groups["clients"].Value;
var newClients = string.Join(",", clientlist.Split('^').Select(s => string.Format("<strong>{0}</strong>", s)));
return newClients + m.Groups["text"];
});
I am very new to regex so any help is appreciated.
I'm new to C# so forgive me if I make rookie mistakes :)
const string pattern = #"\^\^([^-]+)(-[^|]+)\|\^\^";
var temp = Regex.Replace(html, pattern, "<strong>$1</strong>$2");
var result = Regex.Replace(temp, #"\^", "</strong>, <strong>");
I'm using $1 even though MSDN is vague about using that syntax to reference subgroups.
Edit: if it's possible that the text after - contains a ^ you can do this:
var result = Regex.Replace(temp, #"\^(?=.*-)", "</strong>, <strong>");

C#- Validation for US or Canadian zip code

I am using following method to validate US or Canadian zip code, but i think it is not working fine for me. Please suggest me the changes in the regular expression.
private bool IsUSorCanadianZipCode(string zipCode)
{
bool isValidUsOrCanadianZip = false;
string pattern = #"^\d{5}-\d{4}|\d{5}|[A-Z]\d[A-Z] \d[A-Z]\d$";
Regex regex = new Regex(pattern);
return isValidUsOrCanadianZip = regex.IsMatch(zipCode);
}
Thanks.
var _usZipRegEx = #"^\d{5}(?:[-\s]\d{4})?$";
var _caZipRegEx = #"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$";
private bool IsUSOrCanadianZipCode(string zipCode)
{
var validZipCode = true;
if ((!Regex.Match(zipCode, _usZipRegEx).Success) && (!Regex.Match(zipCode, _caZipRegEx).Success))
{
validZipCode = false;
}
return validZipCode;
}
}
If you are using Data Annotation Validators, you can use a RegularExpression attribute like this:
[RegularExpression(#"(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstv‌​xy]{1} *\d{1}[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvxy]{1}\d{1}$)", ErrorMessage = "That postal code is not a valid US or Canadian postal code.")]
(regex is from the link #huMptyduMpty posted above at http://geekswithblogs.net/MainaD/archive/2007/12/03/117321.aspx but my regex allows both upper and lower case letters)
The US zipcode validation which works "on my machine" is
[RegularExpression(#"\d{5}$", ErrorMessage = "Invalid Zip Code")]

Categories

Resources