0

In ASP.NET Core 2.2 MVC model, I have an attribute defined like

[Required, DataType(DataType.EmailAddress)]
public string StudentEmail { get; set; }

This one seems to be perfect for validating Email on user end. But what I want is to validate Email that ends with @mit.edu. Example of Accepting Emails are :

  • john@mit.edu
  • amy@mit.edu

I want to reject all Emails without this format. Is there any way to define through (even if with regex) attributes in the model class?

Shunjid Rahman
  • 409
  • 5
  • 17

2 Answers2

2

EmailAddressAttribute is a sealed class,we can't use EmailAddressAttribute to create custom validation class derived from it, but you can extend from ValidationAttribute when creating specific validation rules to email address field instead using default one.

public class CustomEmailAddressAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {

        Regex rgx = new Regex(@"[a-z0-9._%+-]+@mit.edu");
        if(!rgx.IsMatch(value.ToString()))
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }

    public string GetErrorMessage()
    {
        return $"Please enter a valid email which ends with @mit.edu";
    }
}

Model:

[CustomEmailAddress]
public string StudentEmail { get; set; }

Or you could directly use regex validation, you could use below validation simply:

[RegularExpression(@"[a-z0-9._%+-]+@mit.edu", ErrorMessage = "Please enter a valid email which ends with @mit.edu")]
public string StudentEmail { get; set; }
Ryan
  • 19,118
  • 10
  • 37
  • 53
1

Based on How to validate an email address using a regular expression? post, maybe something like this could work:

((?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@mit\.edu)

This validates also the mail prefix itself. If you only need the suffix part, maybe this?

 .+@mit\.edu
Eaden
  • 33
  • 8