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 :

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?

1
  • Something like [RegularExpression(@".+@mit\.edu", ErrorMessage = "You must use your mycompany email to register")]? Commented Sep 20, 2019 at 12:11

2 Answers 2

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._%+-][email protected]");
        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._%+-][email protected]", ErrorMessage = "Please enter a valid email which ends with @mit.edu")]
public string StudentEmail { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.