Home > OS >  Using model data annotation validation in MVC to ensure a paragraph contain email pattern string
Using model data annotation validation in MVC to ensure a paragraph contain email pattern string

Time:12-19

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.

  1. "My email is [email protected] , [email protected]"
  2. "[email protected];[email protected]"
  3. "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

  1. My Name is John
  2. 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;
      }
 }
  • Related