0

I have the following code but it's not quite working... Any ideas where i'm going wrong? It seems to be failing when there is a carriage return in the string? (see fiddles at bottom)

[RegularExpression(@"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3})))).)*$", ErrorMessage = "Please do not include an email address in your description.")]

Context

People are writing descriptions and also placing email addresses in them, for example:

"Hi there i'm bob, here is my email: example@exampele.com. Hope you havea great day at my party."

I need to check that string and see that there is an email, and then not allow it to be submitted. (I'm using Entity framework and data annotations alongside the jquery validation in ASP .NET MVC 5... This is why i mentioned Data annotation usage.

Note:

I took the inversion technique from here:

Jquery validation on matching 'password' and 'admin' not working

And the email validation from here:

Best Regular Expression for Email Validation in C#

Attempts:

The following string:

http://pastebin.com/00BE7tUW

will show the error, whereas this will not:

http://pastebin.com/i69uxzRf

So something is a little wrong in the expression considering there is no email in it?

Fiddle:
Not working: https://regex101.com/r/zL7xD7/1
Working: https://regex101.com/r/hJ8fJ9/1
Working with email: https://regex101.com/r/dB3cU2/1

Community
  • 1
  • 1
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233

2 Answers2

0

Have you tried something like this:

    bool invalid = false;

       public bool IsValidEmail(string strIn)
       {
           invalid = false;
           if (String.IsNullOrEmpty(strIn))
              return false;

           // Use IdnMapping class to convert Unicode domain names. 
           try {
              strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper,
                                    RegexOptions.None, TimeSpan.FromMilliseconds(200));
           }
           catch (RegexMatchTimeoutException) {
             return false;
           }

            if (invalid)
               return false;

           // Return true if strIn is in valid e-mail format. 
           try {
              return Regex.IsMatch(strIn,
                    @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                    @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                    RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
           }
           catch (RegexMatchTimeoutException) {
              return false;
           }
       }

   private string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.
      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;
      try {
         domainName = idn.GetAscii(domainName);
      }
      catch (ArgumentException) {
         invalid = true;
      }
      return match.Groups[1].Value + domainName;
   }

The IsValidEmail method returns true if the string contains a valid email address and false if it does not, but takes no other action.

To verify that the email address is valid, the IsValidEmail method calls the Regex.Replace(String, String, MatchEvaluator) method with the (@)(.+)$ regular expression pattern to separate the domain name from the email address. The third parameter is a MatchEvaluator delegate that represents the method that processes and replaces the matched text.

Then you would check the email address by doing something like:

IsValidEmail(emailAddress)

Does this work for you?

Kala J
  • 2,040
  • 4
  • 45
  • 85
  • I updated my OP, see if that clarifies my question a bit (Context part). I also tweaked the title a bit. – Jimmyt1988 May 20 '15 at 22:11
  • So, just to be clear, is it the regex that isn't working or the validation? or Both? – Kala J May 20 '15 at 22:23
  • When i type into my field an email then click out, it brings the error up, if i remove the email and type something else, it takes the error away (GOOD SO FAR)... but there seems to be an issue as it does not always work well... Not sure what it is but on one attempt, a carriage return was bringing the error up and when i removed the carriage return, it was fine.. – Jimmyt1988 May 20 '15 at 22:25
  • hmm strange. That I'm not sure about. – Kala J May 20 '15 at 22:30
  • I've added the failing string and a new expression... i'm not quite sure what i've done wrong. Sorry, now check.. the comment was mucking up the string – Jimmyt1988 May 20 '15 at 22:32
  • Did you copy and paste the same expression twice? – Kala J May 20 '15 at 22:34
  • Quite possible, but that's the one i'm working with now... P.S i had to pastebin the string in the end.. it wouldn't keep the carriage return in it. – Jimmyt1988 May 20 '15 at 22:36
  • I've now added the fiddles i'm having issues with... You can see no email is present, so but confused. – Jimmyt1988 May 20 '15 at 22:40
  • It seems to be failing when there is a carriage return in the string? – Jimmyt1988 May 20 '15 at 23:05
  • @Jimmyt1988, try this pattern: pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"; – Kala J May 20 '15 at 23:14
  • Give it a try inside the fiddle program: https://regex101.com/r/vY3kU8/1 - It does not seem to match the string because of the carriage return. Basically if you can add a carriage return allowance to the reg ex i have, then you've cracked it! – Jimmyt1988 May 20 '15 at 23:20
  • Can you add: RegexOptions.Singleline to your regex? – Kala J May 20 '15 at 23:26
0

The . needed to be replaced by [\S\s]

[RegularExpression(@"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))))[\S\s])*$", ErrorMessage = "Please do not include an email address in your field description.")]

source: Regular expression is not matching new lines

Community
  • 1
  • 1
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233