I am try to create text box validation in ASP.NET MVC using C# and the System.ComponentModel.DataAnnotations
namepsace. The textbox shall accept natural human language and allow 1 or multiple emails value...
This is my current code
[RegularExpression(@"([a-zA-Z0-9 ._-] @[a-zA-Z0-9._-] \.[a-zA-Z0-9_-] )", ErrorMessage = "Value Input on box1 must contain email object")]
public string Email_RawInput_1 { get; set; }
so if user key in something like this, it shall pass and not return error message in the UI.
- "My email is [email protected] , [email protected]"
- "[email protected];[email protected]"
- "I don't have email and I use my sister email , [email protected]"
but if user key in something like below, it shall fail validation
- My Name is John
- I like to swim
How can I make this happen using the System.ComponentModel.DataAnnotations
namespace?
CodePudding user response:
if you want to use Data Annotations you can create a custom attribute you can find lots of samples online. and then decorate your property with your custom attribute
public CheckEmailAttribute : ValidationAttribute
{
public override IsValid(object value)
{
var text = value as string;
if (this.DoesContainEmail(text))
{
return true;
}
// does not contain an Email address
return false;
}
private bool DoesContainEmail(string text)
{
return Regex.IsMatch(text,@"([a-zA-Z0-9 ._-] @[a-zA-Z0-9._-] \.[a-zA-Z0-9_-] )" );
}
}
and there is another way please take a look at this link maybe you find it a useful library
CodePudding user response:
using System.Net.Mail;
private boolean EmailValidation(ByVal _emailAddress)
{
try
{
MailAddress m = new MailAddress(_emailAddress)
return true;
}
catch (Exception ex)
{
return false;
}
}