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.
but if user key in something like below, it shall fail validation
How can I make this happen using the System.ComponentModel.DataAnnotations
namespace?
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
using System.Net.Mail;
private boolean EmailValidation(ByVal _emailAddress)
{
try
{
MailAddress m = new MailAddress(_emailAddress)
return true;
}
catch (Exception ex)
{
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.