I have a domain name validation to be kept for a field .For this purpose I use
[DataType(DataType.Url)](a System.ComponentModel.DataAnnotations library of .net).
In this I am not able to allow hypen in between anywhere. What can be the possible change I can make to allow hypen here.
You need to add Regular Expression
[RegularExpression("^.*(?=.{8,})[\\w.]+#[\\w.-]+[.][a-zA-Z0-9]+$", ErrorMessage = "Invalid Email")]
public string Email { get; set; }
For more info about excepting hyphen in domain using regex
Email verification regex failing on hyphens
Related
How to implement this regex \b[A-Za-z0-9._%-]+#(live\.wcs\.ac\.uk)\b to a regular expression check via data annotations in ASP.NET core.
[Required]
[RegularExpression(\b[A-Za-z0-9._%-]+#(live\.wcs\.ac\.uk)\b)]
public string Email {get; set; }
This is how I'm trying to set it as I want there to be #live.wcs.ac.uk as a validation check but my IDE does not like the input I'm trying above.
Any help with a quick explaination of how to set up the annotation properly?
Regex in C# should be declared as a string object, i.e.:
[RegularExpression(#"\b[A-Za-z0-9._%-]+#(live\.wcs\.ac\.uk)\b")]
I think it might be better if you use:
[EmailAddress(ErrorMessage = "your error message here")]
More info here
I am developing a site that uses the built in account model / controller that comes with the new MVC site template. I want to be able to only allow people to register if they use one of two specific domains in their email address.
So for example they can register if they use #domain1.co.uk or #domain2.co.uk, but no other domains (for example Gmail, Yahoo etc) can be used.
If anyone could point me in the right direction that would be great.
If using the MVC3 default site, you'll have a /Models/AccountModels.cs file. You can add a regular expression there to cause client-side* and server-side validation.
public class RegisterModel
{
...
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[RegularExpression(#"^[a-zA-Z0-9._%+-]+(#domain1\.co\.uk|#domain2\.co\.uk)$", ErrorMessage = "Registration limited to domain1 and domain2.")]
public string Email { get; set; }
...
}
You will need to work out the expression that works out best for your requirements.
*client-side validation assumes your view references the jquery.validate script and has Html.ValidationMessageFor(m => m.Email) and/or Html.ValidationSummary(), which it should by default.
What more do you need than:
if( email.Contains("#domain1.co.uk") || email.Contains("#domain2.co.uk") )
Register(email);
else
throw, return false, whatever()
When it comes time to do your validation, i.e. is the email field populated, use a regex to make sure it is in the domain. As for what the actual regex should be, there is a lot of discussion online about validating email addresses with them. It even comes down to what a valid email address should contain. I found this example online, but it likely by no means the best solution, as I am not a regex expert. I have tried it with a few examples but I'm sure you can come up with some that will pass when they shouldn't:
^\w+([-+.']\w+)*#mail.com$
Where mail.com is the domain you want to check against. If you have multiple domains, you can either extend the regex or do multiple checks replacing mail.com in the regex with whatever else you want to use.
BTW I found that regex on this forums.asp.net post which touches on an issue like yours.
Validate that on both the frontend (the reg form) and the backend.
Here I recommend jquery validation plugin for client side validation.
In validating email addresses I have tried using both the EmailAddressAttribute class from System.ComponentModel.DataAnnotations:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
and the MailAddress class from System.Net.Mail by doing:
bool IsValidEmail(string email)
{
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch {
return false;
}
}
as suggested in C# code to validate email address. Both methods work in principle, they catch invalid email addresses like, e.g., user#, not fulfilling the format user#host.
My problem is that none of the two methods detect invalid characters in the user field, such as æ, ø, or å (e.g. åge#gmail.com). Is there any reason for why such characters are not returning a validation error? And do anybody have a elegant solution on how to incorporate a validation for invalid characters in the user field?
Those characters are not invalid. Unusual, but not invalid. The question you linked even contains an explanation why you shouldn't care.
Full use of electronic mail throughout the world requires that
(subject to other constraints) people be able to use close variations
on their own names (written correctly in their own languages and
scripts) as mailbox names in email addresses.
- RFC 6530, 2012
The characters you mentioned (ø, å or åge#gmail.com) are not invalid. Consider an example: When someone uses foreign language as their email id (French,German,etc.), then some unicode characters are possible. Yet EmailAddressAttribute blocks some of the unusual characters.
You can use international characters above U+007F, encoded as UTF-8.
space and "(),:;<>#[] characters are allowed with restrictions (they are only allowed inside a quoted string, a backslash or double-quote must be preceded by a backslash)
special characters !#$%&'*+-/=?^_`{|}~
Regex to validate this: Link
^(([^<>()[].,;:\s#\"]+(.[^<>()[].,;:\s#\"]+)*)|(\".+\"))#(([^<>()[].,;:\s#\"]+.)+[^<>()[].,;:\s#\"]{2,})
This question already has answers here:
Email address validation using ASP.NET MVC data type attributes
(12 answers)
Closed 8 years ago.
I have an MVC 4 web application and I need to enter and validate some email addresses, without sending an email to the user's email address.
Currently I am using basic regex email validation with this pattern:
[RegularExpression(#"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
ErrorMessage = "Please enter correct email address")]
Although this is validating email addresses, it passes 1#1.1 as a valid email address. For the moment I have a validation that requires symbols # symbols . symbols where the symbols can be numeric/alphabetic and ._- .
I need more standard email validation for my MVC 4 application. How do I do that?
You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5.
Example
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
Expanding on Ehsan's Answer....
If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute Class in code.
private static bool IsValidEmailAddress(string emailAddress)
{
return new System.ComponentModel.DataAnnotations
.EmailAddressAttribute()
.IsValid(emailAddress);
}
If you are considering REGEX to verify email address then read:
I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack
Regex:
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
Or you can use just:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
Why not just use the EmailAttribute?
[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }
Don't.
Use a regex for a quick sanity check, something like .#.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.
It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.
It is surprising the question of validating an email address continually comes up on SO!
You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.
Excerpt:
The virtue of my regular expression above is that it matches 99% of
the email addresses in use today. All the email address it matches can
be handled by 99% of all email software out there. If you're looking
for a quick solution, you only need to read the next paragraph. If you
want to know all the trade-offs and get plenty of alternatives to
choose from, read on.
See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:
To all the complainers: after 3 hours experimenting all the solutions
offered in this gigantic discussion, this is THE ONLY good java regex
solution I can find. None of the rfc5322 stuff works on java regex.
In reading about what would be the best way to validate a mail address via regular expressions, I came across with an attempt to validate with
try
{
new MailAddress(input);
}
catch (Exception ex)
{
// invalid
}
What method does the MailAddress class use to ensure a mail address is valid?
You can see the source code without using Reflector using the new .NET Reference Source. Here's the link to the MailAddress class.
If you mean by validate whether or not it's a valid e-mail address format, it supports several standard formats:
The MailAddress class supports the following mail address formats:
A simple address format of user#host. If a DisplayName is not set,
this is the mail address format generated.
A standard quoted display name format of "display name" .
If a DisplayName is set, this is the format generated.
Angle brackets are added around the User name, Host name for "display
name" user#host if these are not included.
Quotes are added around the DisplayName for display name ,
if these are not included.
Unicode characters are supported in the DisplayName. property.
A User name with quotes. For example, "user name"#host.
Consecutive and trailing dots in user names. For example,
user...name..#host.
Bracketed domain literals. For example, .
Comments. For example, (comment)"display
name"(comment)<(comment)user(comment)#(comment)domain(comment)>(comment).
Comments are removed before transmission
.
This is from MailAddress Class
As for what method it uses to validate the formats, I don't know. You could always try Reflector to see what it's doing internally. Is there a particular reason you want to know the internal details?
According to the documentation
The address parameter can contain a display name and the associated
e-mail address if you enclose the address in angle brackets. For
example:
"Tom Smith <tsmith#contoso.com>"
White space is permitted between the display name and the angle
brackets.
So a "naked" address such as tsmith#contos.com or one with a displayed name as mentioned in the documentation is fine. It is impossible to tell how the validation is done internally without access to the code, but a regex doing that validation can of course be constructed.