In register form I use EmailAddress attribute to validate user email.
public class RegisterViewModel
{
[Required(ErrorMessage = "Pole wymagane")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
}
Is there any chance to show what is wrong with email address if validation fails? For example 'oops, I see that your email address contains whitespace'
You have to add another validation for that. Example using [RegularExpression]
public class RegisterViewModel
{
[Required(ErrorMessage = "Pole wymagane")]
[RegularExpression(@"^\S*$", ErrorMessage = "Email Address cannot have white spaces")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
}
You can define your own regular expression for email:
// built-in [EmailAddress] does not allow white spaces around email
public const string EmailValidationRegEx = @"^\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*$";
Note: I have just added white spaces around the existing .NET regex pattern for email match:
"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
Now you can use this new regex pattern instead of [EmailAddress] attribute:
public class RegisterViewModel
{
private string _email;
[Required(ErrorMessage = "Pole wymagane")]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[RegularExpressionWithOptions(EmailValidationRegEx, ErrorMessage = "Invalid email")]
public string Email
{
get => _email;
set
{
_email = string.IsNullOrEmpty(value) ? string.Empty : value.Trim();
}
}
}
Note that I have modified the setter to trim() the value. This ensures that we always get rid of extra white spaces before using the email value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With