0

I am using [EmailAddress] attribute to validate my email input textfield as the following

[EmailAddress]
public string NewBusNotificationEmail { get; set; }

For my testing, I tried the following

test - validation failed

test@ - validation failed

test@test. - validation failed

However, when I tried test@test - validation passed

I also noticed that it does not test for madeup suffix like tets@test.test - validation passed. For test@test, it should be validation fail. Why not? how to fix this?

ramiramilu
  • 17,044
  • 6
  • 49
  • 66
user1250264
  • 897
  • 1
  • 21
  • 54
  • I am getting error for this input `test@test`. I am not getting any error for `test@test.test` and it is acceptable because you cannot validate `ALL` domains using `regex`. By the way, `EmailAddress` attribute validates email string using a regex. – ramiramilu Jan 14 '16 at 19:30
  • 1
    Just now I tested and it is working as expected, i mean showing validation error for `test@test` on both client side and server side (`Model.IsValid`). And as I mentioned in above comment `test@test.test` is a valid input based on regex. Let me know if you have more questions. – ramiramilu Jan 14 '16 at 19:57

1 Answers1

0

if you want limited to some domain you can use Regex .

like this:

[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 create an CustomeAttribute and add some Black List | White List for some domain. this is an example for custome attribute ,

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple  = false)]
public class EmailAddressAttribute : RegularExpressionAttribute
{
    private const string pattern = @"^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$";

static EmailAddressAttribute()
{
    // necessary to enable client side validation
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(RegularExpressionAttributeAdapter));
}

public EmailAddressAttribute() : base(pattern)
{
}
}

Reference :Link

Community
  • 1
  • 1
Uthman Rahimi
  • 708
  • 5
  • 22