I want to be able to do this:
string email = "[email protected]";
bool isValid = IsValidEmail(email);
//returns true
...but use the logic Microsoft has already given us in EmailAddressAttribute.
There are hundreds of good and bad implementations of IsValidEmail out there, and I don't want to add my own, when I can use something, Microsoft has already thought about. It stands to reason, that they will do a better job than me.
In recent ASP.Net versions, we have System.ComponentModel.DataAnnotations, which provides us with the excellent EmailAddressAttribute, that lets us decorate our models like this:
public class SomeModel
{
[EmailAddress]
public string Email { get; set; }
}
The class is sealed, so I cannot call EmailAddressAttribute.IsValid()
Is there a good way I can utilize what Microsoft has already done? Is there a method somewhere in the .Net framework, that let's me test strings against data-annotations, that I have overlooked?
Something along the lines of..:
var emailChecker = new DataAnnotationsChecker<EmailAddressAttribute>();
string email = "[email protected]";
bool isValid = emailChecker.IsValid(email);
//returns true
If you cannot imagine why I would want this, think about getting a List and want to check which ones are valid emails.
You could use the EmailAddressAttribute
to do the validation.
The sealed
means that you cannot create another class that inherits from it. Doesn't mean you cannot use it.
Created some unit tests and works fine
[TestMethod]
public void Should_Use_Email_Address_Attribute_To_Validate_Email() {
var emailChecker = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
string email = "[email protected]";
bool isValid = emailChecker.IsValid(email);
Assert.IsTrue(isValid);
}
[TestMethod]
public void Should_Use_Email_Address_Attribute_To_Invalidate_Email() {
var emailChecker = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
string email = "some@emai l.com";
bool isValid = emailChecker.IsValid(email);
Assert.IsFalse(isValid);
}