I need a very general and loose regular expression for an email.
It just needs to validate that there is an @ in the email string.
For example:
- a@a = valid
- a.@___asdsadc = valid
- aaaaa@sdsdc.com = valid
- ssdsadsadassd = invalid
I currently got up to here:
public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
{
public EmailAttribute()
//: base("[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-_]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-_]*[A-Za-z0-9])?")
: base(".*@.*")
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var errorMessage = FormatErrorMessage(metadata.GetDisplayName());
yield return new EmailValidationRule(errorMessage);
}
}
public class EmailValidationRule : ModelClientValidationRule
{
public EmailValidationRule(string errorMessage)
{
ErrorMessage = errorMessage;
ValidationType = "email";
}
}
So the first one is too tight, and the 2nd one does not seem to return the correct value - I am still being told my string is invalid.
Is it because my regex is wrong? I suspect this validator might not be the same as the rest, as the validatorType is "email", and thus it has worked without me needing to register it as an unobtrusive validator.
It doesn't have to be a proper regex, it just has to be able to validate anything as long as it has the @ symbol on it.
I've used this site to validate my regex: http://gskinner.com/RegExr/ It says my test strings are valid, but this attribute does not pick up changes.