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.
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 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
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.
I've got a regular expression that I am using to check against a string to see if it an email address:
#"^((([\w]+\.[\w]+)+)|([\w]+))#(([\w]+\.)+)([A-Za-z]{1,3})$"
This works fine for all the email addresses I've tested, provided the bit before '#' is at least four characters long.
Works:
web1#domain.co.uk
Doesn't work:
web#domain.co.uk
How can I change the regex to allow prefixes of less than 4 characters??
The 'standard' regex used in asp.net mvc account models for email validation is as follows:
#"^[\w-]+(\.[\w-]+)*#([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$"
It allows 1+ characters before the #
I believe the best way to check a valid email address is to make the user type it twice and then send him an email and challenge the fact that he received it using a validation link.
Check your regex againt a list of weird valid email addresses and you will see regexes are not perfect for email validation tasks.
I recommend not using a regex to validate email (for reasons outlined here) http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/
If you can't sent a confirmation email a good alternative in C# is to try creating a MailAddress and check if it fails.
If you're using ASP.NET you can use a CustomValidator to call this validation method.
bool isValidEmail(string email)
{
try
{
MailAddress m = new MailAddress(email);
return true;
}
catch
{
return false;
}
}
You can use this regex as an alternative:
^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$
Its description can be found here.
About your regex, the starting part (([\w]+\.[\w]+)+) forces the email address to have four characters at the beginning. Emending this part
would do the work for you.
The little trick used in the validated answer i.e. catching exceptions on
new MailAddress(email);
doesn't seem very satisfying as it considers "a#a" as a valid adress in fact it does't raise an exception for almost any string matching the regex "*.#.*" which is clearly too permissive for example
new MailAddress("¦#°§¬|¢#¢¬|")
doesn't raise an exception.
Thus I clearly would go for regex matching
This example is quite satisfying
https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx
You can also try this one
^[a-zA-Z0-9._-]*#[a-z0-9._-]{2,}\.[a-z]{2,4}$
I was wondering if anybody has found a solution that validates an email that includes unicode characters as in from a unicode domain? I have searched at length and have yet to find a solution that works.
Fully validating an email address through a regex is hard. Really hard. This is one that is fully compliant with RFC822. Even if you create a perfect regex that correct validates all email addresses, that doesn't stop me from entering hi#hi.com (If you're trying to make sure that I enter a valid email address) or from accidentally misspelling my username (If you're trying to make sure that I enter my email address correctly).
Just send a link in an email saying, "click here to validate your email address."
I had the same issue and came up with an intelligent solution \p{L}.
Please check it out:
private static bool IsEmailValid(string email) {
System.Text.RegularExpressions.Regex re = new Regex(#"^[\p{L}0-9!$'*+\-_]+(\.[\p{L}0-9!$'*+\-_]+)*#[\p{L}0-9]+(\.[\p{L}0-9]+)*(\.[\p{L}]{2,})$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
return re.IsMatch(email);
}
Ok, so the only email validation I ever found that was truly awesome (instead of just OK) is part of the Zend Framework. Of course that means PHP, hopefully though, you can look at how they do it and emulate some of their better ideas: http://pastebin.com/SvZPBp31 Or just look up Zend_Validate_EmailAddress sourcecode.
sorry that this isn't in C# syntax / language.
Like has been pointed out, validating e-mail addresses through a regular expression is a hard problem. You can get close with a fairly simple one, but there are many, many cases that it will fail to catch. I'm all for sending an email to a supposed email address as #Nick ODell suggests (after doing some basic sanity checking, like, does it contain an # sign, does the domain name portion exist and have one or more of MX/A/AAAA RRs, and the likes) and including a verification link.
That said, if by Unicode domain you mean a Punycode-encoded host name label, those should be covered by any half-way competent validation regexp, as in encoded form those are just xn-- followed by the regular set [a-z0-9-] (case insensitive comparison).