Email Address Validation Using ASP.NET MVC Data Type Attributes

ASP.NET MVC Data annotation validator for email or phone

You can achieve this using Regex. You have to combine the regex for email and phone together.

public class RegisterViewModel
{
[Required]
[Display(Name = "Email or Phone")]
/* /<email-pattern>|<phone-pattern>/ */
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}", ErrorMessage = "Please enter a valid email address or phone number")]
public string EmailOrPhone { get; set; }
}

Or You can create a custom attribute

 public class EmailOrPhoneAttribute : RegularExpressionAttribute
{
public EmailOrPhoneAttribute()
: base(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}")
{
ErrorMessage = "Please provide a valid email address or phone number";
}
}

and use that

 public class RegisterViewModel
{
[Required]
[Display(Name = "Email or Phone")]
[EmailOrPhone]
public string EmailOrPhone { get; set; }
}

Email address validation in C# MVC 4 application: with or without using Regex

You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5.
Example

[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

mvc [DataType(DataType.EmailAddress) no validation

At the moment I have solved my problem using
DataAnnotationsExtensions

it just works, you add their library with NuGet

using DataAnnotationsExtensions;

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

Uses of Datatype.EmailAddress in asp/.net/mvc

So, you are asking what this data type does not why isn't it validating, correct? Per the MSDN, DataType attributes are used primarily for formatting and not validation (which you have learned). What this attribute should do, is when using the Html.DisplayFor() helper, render the field as a clickable hyperlink.

@Html.DisplayFor(x=>x.UserName)

Renders

<a href="mailto:{0}">{0}</a>

Additionally, as pointed out by Zhaph in the comments below, using it in the Html.EditorFor() will generate an HTML 5 email input, which looks something like this:

<input type="email".../>

From MSDN

The following example uses the DataTypeAttribute to customize the
display of EmailAddress data field of the customer table in the
AdventureWorksLT database. The e-mail addresses are shown as
hyperlinks instead of the simple text that ASP.NET Dynamic Data would
have inferred from the intrinsic data type.

DataAnnotations for valid email address

The unexpected validation you are seeing is coming from your browser. If you add the "novalidate" attribute to your form it will disable it:

e.g.

<form asp-controller="Home" asp-action="RegisterAsync" method="post" class="register-form" novalidate>

Specific Email Address Validation - .NET Core MVC Model

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; }


Related Topics



Leave a reply



Submit